import { ws } from '@/api/index'; var socket; var onMsgEvents = []; const MAX_TRY_TIMES = 5; let tryTimes = 0; function startSocket() { if (socket) { socket.close(); } const url = 'ws://' + ws + '/ws'; socket = new WebSocket(url); // 与服务器建立连接:发送消息到服务器 socket.onopen = () => { console.log('connect: '); }; // 收到服务器发送的消息:event处理服务器返回的数据 socket.onmessage = (event) => { // console.log('receive: ', event.data); onMsgEvents.forEach((e) => { if (typeof e === 'function') { e(event.data); } }); }; // 连接或通信过程中发生错误 socket.onerror = (event) => { console.log('errror: ', event); }; // 与服务器断开连接 socket.onclose = (event) => { console.log('close: ', event.code); // setTimeout(() => { // if (tryTimes < MAX_TRY_TIMES) { // startSocket(); // tryTimes++; // } else { // tryTimes = 0; // } // }, 5000); }; } if (socket == undefined) { startSocket(); } function send(value) { if (socket && socket.readyState == WebSocket.OPEN) { socket.send(value); } } function registerReceiveEvent(event) { if (onMsgEvents.indexOf(event) == -1) { onMsgEvents.push(event); } } function removeReceiveEvent(event) { const index = onMsgEvents.indexOf(event); if (index != -1) { onMsgEvents.splice(index, 1); } } export default { send, registerReceiveEvent, removeReceiveEvent };