websocket_sdk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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){
  262. uni.request({
  263. url: baseUrlNew + '/auth/api/loginEnhanced',
  264. data: {
  265. // companyName: "佳屹农",
  266. // password: "y123456",
  267. // username: "jyn"
  268. companyName: "易粮易运",
  269. password: "y123456",
  270. username: "13333333333"
  271. },
  272. method: 'POST',
  273. success: (res) => {
  274. if (res.statusCode === 200) {
  275. uni.setStorageSync('pcUserInfo', res.data)
  276. }
  277. }
  278. })
  279. }
  280. uni.request({
  281. url: baseUrlNew + '/salePlanInfo/getTips',
  282. data: {
  283. phone: userInfo.phone
  284. },
  285. method: 'GET',
  286. success: (res) => {
  287. console.log("websocket myTips",res)
  288. if (res.data.data) {
  289. let name = 'myTip';
  290. let value = res.data.data.myTip;
  291. store.commit('$uStore', {
  292. name,
  293. value
  294. });
  295. if(value != 0){
  296. uni.setTabBarBadge({
  297. index:3,
  298. text:value+""
  299. })
  300. }
  301. name = 'taskTip';
  302. value = res.data.data.taskTip;
  303. store.commit('$uStore', {
  304. name,
  305. value
  306. });
  307. name = 'contractTip';
  308. value = res.data.data.contractTip;
  309. store.commit('$uStore', {
  310. name,
  311. value
  312. });
  313. }
  314. }
  315. })
  316. // let accessToken = userInfo ? userInfo.accessToken : ''
  317. // var data = {}
  318. // var _mt = 'getTips'
  319. // var _gp = 'integral'
  320. // uni.request({
  321. // url: baseUrl + '/m.api',
  322. // data: {
  323. // ...data,
  324. // _gp,
  325. // _mt
  326. // },
  327. // method: 'POST',
  328. // header: {
  329. // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  330. // 'ACCESSTOKEN': accessToken
  331. // },
  332. // success: (res) => {
  333. // if (res.statusCode === 200) {
  334. // let name = 'myTip';
  335. // let value = res.data.data.myTips;
  336. // store.commit('$uStore', {
  337. // name,
  338. // value
  339. // });
  340. // name = 'taskTip';
  341. // value = res.data.data.task;
  342. // store.commit('$uStore', {
  343. // name,
  344. // value
  345. // });
  346. // name = 'contractTip';
  347. // value = res.data.data.contract;
  348. // store.commit('$uStore', {
  349. // name,
  350. // value
  351. // });
  352. // }
  353. // }
  354. // })
  355. })
  356. }
  357. getInfo(){
  358. return new Promise(resolve => {
  359. var hour = new Date().getHours();
  360. if((hour >= 9 && hour < 12) ||(hour >= 13 && hour < 15)){
  361. var infoList = [];
  362. uni.request({
  363. url: "https://hq.sinajs.cn/list=C0,C2109,C2111,C2201,C2203,C2205,C2207,A0,A2109,A2111,A2201,A2203,A2205,A2207",
  364. // url: "https://hq.sinajs.cn/list=C2109",
  365. header: {
  366. 'content-type': 'application/x-www-form-urlencoded'
  367. },
  368. success: function(result) {
  369. // resolve调用后,即可传递到调用方使用then或者async+await同步方式进行处理逻辑
  370. var tmp = result.data.split('"')
  371. for(var i = 1; i<tmp.length;i=i+2){
  372. var list = tmp[i].split(",")
  373. var data = {
  374. goodsName:list[0],
  375. newPrice:list[6],
  376. openPrice:list[2]
  377. }
  378. if(data.goodsName){
  379. infoList.push(data)
  380. }
  381. }
  382. let name = 'infoList';
  383. let value = infoList;
  384. store.commit('$uStore', {
  385. name,
  386. value
  387. });
  388. // console.log("infoList",infoList)
  389. },
  390. fail: function(e) {
  391. console.log('error in...')
  392. // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
  393. reject(e)
  394. },
  395. })
  396. }
  397. })
  398. }
  399. }