websocket_sdk.js 11 KB

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