websocket.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // src/utils/websocket.js
  2. import { wsConfig } from "@/config";
  3. class WebSocketClient {
  4. constructor(url) {
  5. this.url = url;
  6. this.ws = null;
  7. this.reconnectTimeout = null;
  8. }
  9. // 初始化 WebSocket 连接
  10. connect(callback) {
  11. if (this.ws) {
  12. console.warn("WebSocket 已经连接");
  13. return;
  14. }
  15. this.ws = new WebSocket(this.url);
  16. // 连接成功
  17. this.ws.onopen = () => {
  18. console.log("WebSocket 连接成功:", this.url);
  19. if (callback) callback(true);
  20. };
  21. // 接收消息
  22. this.ws.onmessage = (event) => {
  23. console.log("收到 WebSocket 消息:", event.data);
  24. };
  25. // 连接关闭
  26. this.ws.onclose = () => {
  27. console.log("WebSocket 连接关闭,尝试重连...");
  28. this.ws = null;
  29. this.reconnect();
  30. };
  31. // 连接错误
  32. this.ws.onerror = (error) => {
  33. console.error("WebSocket 错误:", error);
  34. this.ws.close();
  35. };
  36. }
  37. // 发送消息
  38. sendMessage(message) {
  39. if (this.ws && this.ws.readyState === WebSocket.OPEN) {
  40. this.ws.send(message);
  41. } else {
  42. console.warn("WebSocket 未连接,消息发送失败");
  43. }
  44. }
  45. // 关闭 WebSocket
  46. close() {
  47. if (this.ws) {
  48. this.ws.close();
  49. }
  50. }
  51. // 断线重连
  52. reconnect() {
  53. if (this.reconnectTimeout) clearTimeout(this.reconnectTimeout);
  54. this.reconnectTimeout = setTimeout(() => {
  55. console.log("尝试重新连接 WebSocket...");
  56. this.connect();
  57. }, 3000);
  58. }
  59. }
  60. // 导出 WebSocket 客户端
  61. export const wsClient = new WebSocketClient(wsConfig.equipmentList);
  62. //导出树状结构WebSocket客户端
  63. export const wsClientTree = new WebSocketClient(wsConfig.equipmentTree);