Newer
Older
Nanping_sponge_GCYPG / src / store / modules / websocket.js
@liyingjing liyingjing on 25 Oct 2023 1 KB 工程预评估
  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. // console.log("收到的数据:", JSON.parse(e.data));
  30. that.count++;
  31. that.data = JSON.parse(e.data);
  32. // console.log(that.count);
  33. };
  34. this.webSocket.onerror = function () {
  35. console.log("通讯异常");
  36. };
  37. this.webSocket.onclose = function () {
  38. console.log("连接已断开");
  39. this.timer && clearInterval(this.timer);
  40. };
  41. },
  42. },
  43. });
  44.  
  45. export default websocketStore;