websocket_sdk.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. },
  262. method: 'POST',
  263. success: (res) => {
  264. if (res.statusCode === 200) {
  265. uni.setStorageSync('pcUserInfo', res.data)
  266. }
  267. }
  268. })
  269. }
  270. let accessToken = userInfo ? userInfo.accessToken : ''
  271. var data = {}
  272. var _mt = 'getTips'
  273. var _gp = 'integral'
  274. uni.request({
  275. url: baseUrl + '/m.api',
  276. data: {
  277. ...data,
  278. _gp,
  279. _mt
  280. },
  281. method: 'POST',
  282. header: {
  283. 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
  284. 'ACCESSTOKEN': accessToken
  285. },
  286. success: (res) => {
  287. if (res.statusCode === 200) {
  288. let name = 'myTip';
  289. let value = res.data.data.myTips;
  290. store.commit('$uStore', {
  291. name,
  292. value
  293. });
  294. name = 'taskTip';
  295. value = res.data.data.task;
  296. store.commit('$uStore', {
  297. name,
  298. value
  299. });
  300. name = 'contractTip';
  301. value = res.data.data.contract;
  302. store.commit('$uStore', {
  303. name,
  304. value
  305. });
  306. }
  307. }
  308. })
  309. })
  310. }
  311. getInfo(){
  312. return new Promise(resolve => {
  313. var hour = new Date().getHours();
  314. if((hour >= 9 && hour < 12) ||(hour >= 13 && hour < 15)){
  315. var infoList = [];
  316. uni.request({
  317. url: "https://hq.sinajs.cn/list=C0,C2109,C2111,C2201,C2203,C2205,C2207,A0,A2109,A2111,A2201,A2203,A2205,A2207",
  318. // url: "https://hq.sinajs.cn/list=C2109",
  319. header: {
  320. 'content-type': 'application/x-www-form-urlencoded'
  321. },
  322. success: function(result) {
  323. // resolve调用后,即可传递到调用方使用then或者async+await同步方式进行处理逻辑
  324. var tmp = result.data.split('"')
  325. for(var i = 1; i<tmp.length;i=i+2){
  326. var list = tmp[i].split(",")
  327. var data = {
  328. goodsName:list[0],
  329. newPrice:list[6],
  330. openPrice:list[2]
  331. }
  332. if(data.goodsName){
  333. infoList.push(data)
  334. }
  335. }
  336. let name = 'infoList';
  337. let value = infoList;
  338. store.commit('$uStore', {
  339. name,
  340. value
  341. });
  342. // console.log("infoList",infoList)
  343. },
  344. fail: function(e) {
  345. console.log('error in...')
  346. // reject调用后,即可传递到调用方使用catch或者async+await同步方式进行处理逻辑
  347. reject(e)
  348. },
  349. })
  350. }
  351. })
  352. }
  353. }