websocket_sdk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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. showCancel: false,
  143. success: function(res) {
  144. if (res.confirm) {
  145. console.log('用户点击确定')
  146. }
  147. }
  148. })
  149. }
  150. }
  151. })
  152. }
  153. }
  154. // 发送websocket消息
  155. sendWebSocketMsg(options) {
  156. this.sendBinary(1,options);
  157. }
  158. //发送心跳连接
  159. sendHeartbeatData(options) {
  160. var that = this
  161. let packet = {
  162. version: 1,
  163. command: 17,
  164. token: store.state.userData.token
  165. }
  166. this.sendBinary(99, {
  167. data: packet,
  168. success(res) {
  169. // console.log('【websocket】心跳连接成功');
  170. if(!that._showLoginDialog){
  171. that._showLoginDialog= true
  172. }
  173. },
  174. fail(err) {
  175. console.log('【websocket】心跳连接失败');
  176. console.log(err)
  177. console.log('this._showLoginDialog',that._showLoginDialog )
  178. uni.hideLoading()
  179. that._isLogin = false
  180. that._reConnect(options)
  181. }
  182. });
  183. }
  184. //发送第一次连接数据
  185. sendLoginData() {
  186. this.sendBinary(99, {
  187. data: {},
  188. success(res) {
  189. console.log('【websocket】第一次连接成功')
  190. },
  191. fail(err) {
  192. console.log('【websocket】第一次连接失败')
  193. console.log(err)
  194. }
  195. });
  196. // this.sendBinary(99, {});
  197. // socket.sendSocketMessage({
  198. // // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
  199. // data: JSON.stringify({
  200. // "key": 'value'
  201. // })
  202. // })
  203. }
  204. // 重连方法,会根据时间频率越来越慢
  205. _reConnect(options) {
  206. let timer, _this = this;
  207. if (this._connectNum < 20) {
  208. timer = setTimeout(() => {
  209. this.initWebSocket(options)
  210. }, 500)
  211. this._connectNum += 1;
  212. } else if (this._connectNum < 50) {
  213. timer = setTimeout(() => {
  214. this.initWebSocket(options)
  215. }, 1000)
  216. this._connectNum += 1;
  217. } else {
  218. timer = setTimeout(() => {
  219. this.initWebSocket(options)
  220. }, 3000)
  221. this._connectNum += 1;
  222. }
  223. }
  224. // 关闭websocket连接
  225. closeWebSocket() {
  226. uni.closeSocket();
  227. this._isClosed = true;
  228. }
  229. //发送二进制
  230. sendBinary(commendType, options) {
  231. uni.sendSocketMessage({
  232. data: packetCode.encode(options.data),
  233. success(res) {
  234. if (typeof options.success == "function") {
  235. options.success(res)
  236. } else {
  237. console.log('参数的类型必须为函数')
  238. }
  239. },
  240. fail(err) {
  241. if (typeof options.fail == "function") {
  242. options.fail(err)
  243. } else {
  244. console.log('参数的类型必须为函数')
  245. }
  246. }
  247. });
  248. }
  249. getTips(){
  250. return new Promise(resolve => {
  251. let baseUrl = config.def().baseUrl
  252. let baseUrlNew = config.def().baseUrlNew
  253. var userInfo
  254. if (!userInfo || !userInfo.accessToken) {
  255. userInfo = uni.getStorageSync('userInfo')
  256. }
  257. var pcUserInfo=uni.getStorageSync('pcUserInfo')
  258. if(!pcUserInfo){
  259. uni.request({
  260. url: baseUrlNew + '/auth/api/loginEnhanced',
  261. data: {
  262. // companyName: "佳屹农",
  263. // password: "y123456",
  264. // username: "jyn"
  265. companyName: "易粮易运",
  266. password: "y123456",
  267. username: "13333333333"
  268. },
  269. method: 'POST',
  270. success: (res) => {
  271. if (res.statusCode === 200) {
  272. uni.setStorageSync('pcUserInfo', res.data)
  273. }
  274. }
  275. })
  276. }
  277. uni.request({
  278. url: baseUrlNew + '/salePlanInfo/getTips',
  279. data: {
  280. phone: userInfo.phone
  281. },
  282. method: 'GET',
  283. success: (res) => {
  284. console.log("websocket myTips",res)
  285. if (res.data.data) {
  286. let name = 'myTip';
  287. let value = res.data.data.myTip;
  288. store.commit('$uStore', {
  289. name,
  290. value
  291. });
  292. if(value != 0){
  293. uni.setTabBarBadge({
  294. index:3,
  295. text:value+""
  296. })
  297. }
  298. name = 'taskTip';
  299. value = res.data.data.taskTip;
  300. store.commit('$uStore', {
  301. name,
  302. value
  303. });
  304. name = 'contractTip';
  305. value = res.data.data.contractTip;
  306. store.commit('$uStore', {
  307. name,
  308. value
  309. });
  310. }
  311. }
  312. })
  313. // let accessToken = userInfo ? userInfo.accessToken : ''
  314. // var data = {}
  315. // var _mt = 'getTips'
  316. // var _gp = 'integral'
  317. // uni.request({
  318. // url: baseUrl + '/m.api',
  319. // data: {
  320. // ...data,
  321. // _gp,
  322. // _mt
  323. // },
  324. // method: 'POST',
  325. // header: {
  326. // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  327. // 'ACCESSTOKEN': accessToken
  328. // },
  329. // success: (res) => {
  330. // if (res.statusCode === 200) {
  331. // let name = 'myTip';
  332. // let value = res.data.data.myTips;
  333. // store.commit('$uStore', {
  334. // name,
  335. // value
  336. // });
  337. // name = 'taskTip';
  338. // value = res.data.data.task;
  339. // store.commit('$uStore', {
  340. // name,
  341. // value
  342. // });
  343. // name = 'contractTip';
  344. // value = res.data.data.contract;
  345. // store.commit('$uStore', {
  346. // name,
  347. // value
  348. // });
  349. // }
  350. // }
  351. // })
  352. })
  353. }
  354. getInfo(){
  355. return new Promise(resolve => {
  356. var hour = new Date().getHours();
  357. if((hour >= 9 && hour < 12) ||(hour >= 13 && hour < 15)){
  358. var infoList = [];
  359. uni.request({
  360. url: "https://hq.sinajs.cn/list=C0,C2109,C2111,C2201,C2203,C2205,C2207,A0,A2109,A2111,A2201,A2203,A2205,A2207",
  361. // url: "https://hq.sinajs.cn/list=C2109",
  362. header: {
  363. 'content-type': 'application/x-www-form-urlencoded'
  364. },
  365. success: function(result) {
  366. // resolve调用后,即可传递到调用方使用then或者async+await同步方式进行处理逻辑
  367. var tmp = result.data.split('"')
  368. for(var i = 1; i<tmp.length;i=i+2){
  369. var list = tmp[i].split(",")
  370. var data = {
  371. goodsName:list[0],
  372. newPrice:list[6],
  373. openPrice:list[2]
  374. }
  375. if(data.goodsName){
  376. infoList.push(data)
  377. }
  378. }
  379. let name = 'infoList';
  380. let value = infoList;
  381. store.commit('$uStore', {
  382. name,
  383. value
  384. });
  385. // console.log("infoList",infoList)
  386. },
  387. fail: function(e) {
  388. console.log('error in...')
  389. // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
  390. reject(e)
  391. },
  392. })
  393. }
  394. })
  395. }
  396. }