websocket.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import config from '../config'
  2. import storage from './storage'
  3. import {navigateTo} from './utils'
  4. export default {
  5. socketTask: null,
  6. timer: null,
  7. /**
  8. * 创建 WebSocket 连接。
  9. */
  10. connect(){
  11. let users = storage.getJson("users");
  12. let token = storage.getJson("token");
  13. let stationCode=storage.get("stationCode")
  14. if(users == null || token == null){
  15. navigateTo("public/login");
  16. return false;
  17. }
  18. if(this.timer !=null){
  19. clearInterval(this.timer)
  20. this.timer=null
  21. }
  22. if(this.socketTask!=null){
  23. this.socketTask.close();
  24. }
  25. this.socketTask = uni.connectSocket({
  26. url: config.web_socket_url+stationCode+'/'+token,
  27. header: {
  28. 'content-type': 'application/json'
  29. },
  30. complete: ()=> {}
  31. });
  32. // 监听WebSocket连接打开事件。
  33. this.socketTask.onOpen(() => {
  34. console.log('WebSocket连接已打开!');
  35. this.onSocketOpen()
  36. });
  37. //接收服务器数据事件
  38. this.socketTask.onMessage(res=>{
  39. this.onSocketMsg(res)
  40. })
  41. //监听WebSocket关闭事件
  42. this.socketTask.onClose(()=>{
  43. console.log('WebSocket连接已关闭!');
  44. })
  45. this.socketTask.onError(()=>{
  46. console.log("WebSocket连接错误")
  47. })
  48. if(this.timer ==null){
  49. this.timer=setInterval(()=>{
  50. if(this.socketTask.readyState!=1){
  51. this.socketTask.close()
  52. this.connect()
  53. }
  54. },2000)
  55. }
  56. },
  57. onSocketOpen(){},
  58. onSocketMsg(){},
  59. sendmessage(msg){
  60. this.socketTask.send({data:JSON.stringify(msg)})
  61. },
  62. }