socket.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import base from '@/config/baseUrl';
  2. import store from '@/store';
  3. class socket {
  4. constructor(options) {
  5. //地址
  6. this.socketUrl = 'ws://192.168.0.52:8080/websocket/99140109M13D01001';
  7. this.socketStart = false;
  8. this.monitorSocketError();
  9. this.monitorSocketClose();
  10. this.socketReceive();
  11. }
  12. setUrl(url) {
  13. this.socketUrl = url; // 设置新的 WebSocket URL
  14. this.close(); // 关闭当前的连接
  15. this.init(); // 重新初始化连接
  16. }
  17. init(callback) {
  18. const _this = this;
  19. if (base.socketUrl) {
  20. if (this.socketStart) {} else {
  21. uni.connectSocket({
  22. url: this.socketUrl,
  23. method: 'GET'
  24. });
  25. uni.onSocketOpen((res) => {
  26. this.socketStart = true;
  27. callback && callback();
  28. });
  29. setTimeout(() => {
  30. _this.getHeartbeat();
  31. }, 5000);
  32. }
  33. } else {}
  34. }
  35. //Socket给服务器发送消息
  36. send(data, callback) {
  37. const _this = this;
  38. if (store.state.userInfo.uid) {
  39. data.userUid = store.state.userInfo.uid;
  40. }
  41. uni.sendSocketMessage({
  42. data: JSON.stringify(data),
  43. success: () => {
  44. callback && callback(true);
  45. },
  46. fail: () => {
  47. callback && callback(false);
  48. }
  49. });
  50. }
  51. //Socket接收服务器发送过来的消息
  52. socketReceive() {
  53. const _this = this;
  54. uni.onSocketMessage(function(res) {
  55. let data = JSON.parse(res.data);
  56. console.log('收到服务器内容:', data);
  57. _this.acceptMessage && _this.acceptMessage(data);
  58. });
  59. }
  60. //关闭Socket
  61. closeSocket() {
  62. uni.closeSocket();
  63. _this.socketStart = false;
  64. }
  65. //监听Socket关闭
  66. monitorSocketClose() {
  67. const _this = this;
  68. uni.onSocketClose(function(res) {
  69. console.log('WebSocket 已关闭!');
  70. _this.socketStart = false;
  71. setTimeout(function() {
  72. _this.init();
  73. }, 3000);
  74. });
  75. }
  76. //监听Socket错误
  77. monitorSocketError() {
  78. const _this = this;
  79. uni.onSocketError(function(res) {
  80. _this.socketStart = false;
  81. console.log('WebSocket连接打开失败,请检查!');
  82. });
  83. }
  84. //心跳
  85. getHeartbeat() {
  86. const _this = this;
  87. this.send({
  88. type: "心跳",
  89. userUid: store.state.userInfo.userUid
  90. }, (val) => {
  91. setTimeout(() => {
  92. if (val) {
  93. _this.getHeartbeat();
  94. } else {
  95. _this.init();
  96. }
  97. }, 10000);
  98. });
  99. }
  100. };
  101. const mySocket = new socket();
  102. export default mySocket;