Newer
Older
DH_Apicture / src / store / modules / websocket.js
@zhangqy zhangqy on 29 Nov 1 KB first commit
  1. const websocketStore = defineStore("websocket", {
  2. state: () => ({
  3. //推送消息
  4. data: {},
  5. webSocket: null,
  6. timer: null,
  7. hearbeat_interval: 1000 * 2,
  8. count: 0,
  9. }),
  10. actions: {
  11. initWebsocket(url) {
  12. var that = this;
  13. console.log("url", url);
  14. this.webSocket = new WebSocket(
  15. "wss://server1.wh-nf.cn:8132/patrol/websocket/" + url
  16. );
  17. this.webSocket.onopen = function () {
  18. console.log("通讯开始");
  19. this.timer && clearInterval(this.timer);
  20. this.timer = setInterval(() => {
  21. // this.webSocket.send(
  22. // JSON.stringify({
  23. // token: Math.random(),
  24. // })
  25. // );
  26. }, this.hearbeat_interval);
  27. };
  28. this.webSocket.onmessage = function (e) {
  29. // debugger;
  30. // console.log("收到的数据:", JSON.parse(e.data));
  31. that.count++;
  32. that.data = JSON.parse(e.data);
  33. // console.log(that.count);
  34. };
  35. this.webSocket.onerror = function () {
  36. console.log("通讯异常");
  37. };
  38. this.webSocket.onclose = function () {
  39. console.log("连接已断开");
  40. this.timer && clearInterval(this.timer);
  41. };
  42. },
  43. },
  44. });
  45.  
  46. export default websocketStore;