websocket_sdk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import packetCode from './PacketCodeC.js'
  2. import store from './store/index.js'
  3. import * as config from './config'
  4. export default class Websocket {
  5. constructor({
  6. heartCheck,
  7. isReconnection
  8. }) {
  9. // 是否连接
  10. this._isLogin = false;
  11. // 当前网络状态
  12. this._netWork = true;
  13. // 是否人为退出
  14. this._isClosed = false;
  15. // 心跳检测频率
  16. this._timeout = 3000;
  17. this._timeoutObj = null;
  18. this._timeoutObj1 = null;
  19. // 当前重连次数
  20. this._connectNum = 0;
  21. // 心跳检测和断线重连开关,true为启用,false为关闭
  22. this._heartCheck = heartCheck;
  23. this._isReconnection = isReconnection;
  24. this._showLoginDialog = true
  25. // this._onSocketOpened();
  26. }
  27. // 心跳重置
  28. _reset() {
  29. clearTimeout(this._timeoutObj);
  30. clearTimeout(this._timeoutObj1);
  31. return this;
  32. }
  33. // 心跳开始
  34. _start(options) {
  35. let _this = this;
  36. this._timeoutObj = setInterval(() => {
  37. //发送心跳
  38. _this.sendHeartbeatData(options);
  39. _this.getInfo()
  40. }, this._timeout);
  41. this._timeoutObj1 = setInterval(() => {
  42. _this.getTips()
  43. }, 1000*60);
  44. }
  45. // 监听websocket连接关闭
  46. onSocketClosed(options) {
  47. uni.onSocketError(err => {
  48. console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
  49. // 停止心跳连接
  50. if (this._heartCheck) {
  51. this._reset();
  52. }
  53. // 关闭已登录开关
  54. this._isLogin = false;
  55. // 检测是否是用户自己退出小程序
  56. console.log('------------------开启重连--------------------------------')
  57. if (!this._isClosed) {
  58. // 进行重连
  59. if (this._isReconnection) {
  60. this._reConnect(options)
  61. }
  62. }
  63. })
  64. uni.onSocketClose(err => {
  65. })
  66. }
  67. // 检测网络变化
  68. onNetworkChange(options) {
  69. uni.onNetworkStatusChange(res => {
  70. console.log('当前网络状态:' + res.isConnected);
  71. if (!this._netWork) {
  72. this._isLogin = false;
  73. // 进行重连
  74. if (this._isReconnection) {
  75. this._reConnect(options)
  76. }
  77. }
  78. })
  79. }
  80. _onSocketOpened(options) {
  81. uni.onSocketOpen(res => {
  82. console.log('【websocket】已打开');
  83. // 打开已登录开关
  84. this._isLogin = true;
  85. // 发送心跳
  86. if (this._heartCheck) {
  87. this._reset()._start(options);
  88. }
  89. // 发送登录信息
  90. this.sendLoginData();
  91. // 打开网络开关
  92. this._netWork = true;
  93. })
  94. }
  95. // 接收服务器返回的消息
  96. onReceivedMsg(callBack) {
  97. uni.onSocketMessage(event => {
  98. if (typeof callBack == "function") {
  99. callBack(event)
  100. } else {
  101. console.log('参数的类型必须为函数')
  102. }
  103. })
  104. }
  105. // 建立websocket连接
  106. initWebSocket(options) {
  107. let _this = this;
  108. if (this._isLogin) {
  109. console.log("您已经登录了");
  110. } else {
  111. // 检查网络
  112. uni.getNetworkType({
  113. success(result) {
  114. if (result.networkType != 'none') {
  115. // 开始建立连接
  116. console.log('建立websocket连接' + options.url);
  117. uni.connectSocket({
  118. url: options.url,
  119. success(res) {
  120. if (typeof options.success == "function") {
  121. options.success(res)
  122. _this._onSocketOpened(options);
  123. } else {
  124. console.log('参数的类型必须为函数')
  125. }
  126. },
  127. fail(err) {
  128. if (typeof options.fail == "function") {
  129. options.fail(err)
  130. } else {
  131. console.log('参数的类型必须为函数')
  132. }
  133. }
  134. })
  135. } else {
  136. console.log('网络已断开');
  137. _this._netWork = false;
  138. // 网络断开后显示model
  139. // uni.showModal({
  140. // title: '网络错误',
  141. // content: '请重新打开网络',
  142. // success: function(res) {
  143. // if (res.confirm) {
  144. // console.log('用户点击确定')
  145. // }
  146. // }
  147. // })
  148. uni.showToast({
  149. title: "网络错误 请重新打开网络",
  150. icon: 'none'
  151. })
  152. }
  153. }
  154. })
  155. }
  156. }
  157. // 发送websocket消息
  158. sendWebSocketMsg(options) {
  159. this.sendBinary(1,options);
  160. }
  161. //发送心跳连接
  162. sendHeartbeatData(options) {
  163. var that = this
  164. let packet = {
  165. version: 1,
  166. command: 17,
  167. token: store.state.userData.token
  168. }
  169. this.sendBinary(99, {
  170. data: packet,
  171. success(res) {
  172. // console.log('【websocket】心跳连接成功');
  173. if(!that._showLoginDialog){
  174. that._showLoginDialog= true
  175. }
  176. },
  177. fail(err) {
  178. console.log('【websocket】心跳连接失败');
  179. console.log(err)
  180. console.log('this._showLoginDialog',that._showLoginDialog )
  181. uni.hideLoading()
  182. that._isLogin = false
  183. that._reConnect(options)
  184. }
  185. });
  186. }
  187. //发送第一次连接数据
  188. sendLoginData() {
  189. this.sendBinary(99, {
  190. data: {},
  191. success(res) {
  192. console.log('【websocket】第一次连接成功')
  193. },
  194. fail(err) {
  195. console.log('【websocket】第一次连接失败')
  196. console.log(err)
  197. }
  198. });
  199. // this.sendBinary(99, {});
  200. // socket.sendSocketMessage({
  201. // // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
  202. // data: JSON.stringify({
  203. // "key": 'value'
  204. // })
  205. // })
  206. }
  207. // 重连方法,会根据时间频率越来越慢
  208. _reConnect(options) {
  209. let timer, _this = this;
  210. if (this._connectNum < 20) {
  211. timer = setTimeout(() => {
  212. this.initWebSocket(options)
  213. }, 500)
  214. this._connectNum += 1;
  215. } else if (this._connectNum < 50) {
  216. timer = setTimeout(() => {
  217. this.initWebSocket(options)
  218. }, 1000)
  219. this._connectNum += 1;
  220. } else {
  221. timer = setTimeout(() => {
  222. this.initWebSocket(options)
  223. }, 3000)
  224. this._connectNum += 1;
  225. }
  226. }
  227. // 关闭websocket连接
  228. closeWebSocket() {
  229. uni.closeSocket();
  230. this._isClosed = true;
  231. }
  232. //发送二进制
  233. sendBinary(commendType, options) {
  234. uni.sendSocketMessage({
  235. data: packetCode.encode(options.data),
  236. success(res) {
  237. if (typeof options.success == "function") {
  238. options.success(res)
  239. } else {
  240. console.log('参数的类型必须为函数')
  241. }
  242. },
  243. fail(err) {
  244. if (typeof options.fail == "function") {
  245. options.fail(err)
  246. } else {
  247. console.log('参数的类型必须为函数')
  248. }
  249. }
  250. });
  251. }
  252. getTips(){
  253. return new Promise(resolve => {
  254. let baseUrl = config.def().baseUrl
  255. let baseUrlNew = config.def().baseUrlNew
  256. var userInfo
  257. if (!userInfo || !userInfo.accessToken) {
  258. userInfo = uni.getStorageSync('userInfo')
  259. }
  260. var pcUserInfo=uni.getStorageSync('pcUserInfo')
  261. if(!pcUserInfo && userInfo){
  262. uni.request({
  263. url: baseUrlNew + '/commonUser/api/loginQuickly',
  264. data: {
  265. mobilePhone: userInfo.phone,
  266. veriCode: "123456",
  267. },
  268. method: 'POST',
  269. success: (res) => {
  270. if (res.statusCode === 200) {
  271. uni.setStorageSync('pcUserInfo', res.data)
  272. }
  273. else{
  274. uni.request({
  275. url: baseUrlNew + '/commonUser/api/loginQuickly',
  276. data: {
  277. mobilePhone: "13333333333",
  278. veriCode: "123456",
  279. },
  280. method: 'POST',
  281. success: (res) => {
  282. if (res.statusCode === 200) {
  283. uni.setStorageSync('pcUserInfo', res.data)
  284. }
  285. }
  286. })
  287. }
  288. }
  289. })
  290. }
  291. uni.request({
  292. url: baseUrlNew + '/notice/query/noticeNumber',
  293. data: {
  294. },
  295. method: 'GET',
  296. success: (res) => {
  297. if (res.data.data) {
  298. let name = 'myTip';
  299. let value = res.data.data.task;
  300. store.commit('$uStore', {
  301. name,
  302. value
  303. });
  304. if(value != 0&&value){
  305. uni.setTabBarBadge({
  306. index:4,
  307. text:value+""
  308. })
  309. }
  310. name = 'taskTip';
  311. value = res.data.data.task;
  312. store.commit('$uStore', {
  313. name,
  314. value
  315. });
  316. // name = 'contractTip';
  317. // value = res.data.data.contractTip;
  318. // store.commit('$uStore', {
  319. // name,
  320. // value
  321. // });
  322. }
  323. }
  324. })
  325. // let accessToken = userInfo ? userInfo.accessToken : ''
  326. // var data = {}
  327. // var _mt = 'getTips'
  328. // var _gp = 'integral'
  329. // uni.request({
  330. // url: baseUrl + '/m.api',
  331. // data: {
  332. // ...data,
  333. // _gp,
  334. // _mt
  335. // },
  336. // method: 'POST',
  337. // header: {
  338. // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  339. // 'ACCESSTOKEN': accessToken
  340. // },
  341. // success: (res) => {
  342. // if (res.statusCode === 200) {
  343. // let name = 'myTip';
  344. // let value = res.data.data.myTips;
  345. // store.commit('$uStore', {
  346. // name,
  347. // value
  348. // });
  349. // name = 'taskTip';
  350. // value = res.data.data.task;
  351. // store.commit('$uStore', {
  352. // name,
  353. // value
  354. // });
  355. // name = 'contractTip';
  356. // value = res.data.data.contract;
  357. // store.commit('$uStore', {
  358. // name,
  359. // value
  360. // });
  361. // }
  362. // }
  363. // })
  364. })
  365. }
  366. getInfo(){
  367. return new Promise(resolve => {
  368. var hour = new Date().getHours();
  369. if((hour >= 9 && hour < 12) ||(hour >= 13 && hour < 15)){
  370. var infoList = [];
  371. uni.request({
  372. url: "https://hq.sinajs.cn/list=C0,C2109,C2111,C2201,C2203,C2205,C2207,A0,A2109,A2111,A2201,A2203,A2205,A2207",
  373. // url: "https://hq.sinajs.cn/list=C2109",
  374. header: {
  375. 'content-type': 'application/x-www-form-urlencoded'
  376. },
  377. success: function(result) {
  378. // resolve调用后,即可传递到调用方使用then或者async+await同步方式进行处理逻辑
  379. var tmp = result.data.split('"')
  380. for(var i = 1; i<tmp.length;i=i+2){
  381. var list = tmp[i].split(",")
  382. var data = {
  383. goodsName:list[0],
  384. newPrice:list[6],
  385. openPrice:list[2]
  386. }
  387. if(data.goodsName){
  388. infoList.push(data)
  389. }
  390. }
  391. let name = 'infoList';
  392. let value = infoList;
  393. store.commit('$uStore', {
  394. name,
  395. value
  396. });
  397. // console.log("infoList",infoList)
  398. },
  399. fail: function(e) {
  400. console.log('error in...')
  401. // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
  402. reject(e)
  403. },
  404. })
  405. }
  406. })
  407. }
  408. }