websocket_sdk.js 12 KB

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