websocket_sdk.js 12 KB

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