54 lines
1.2 KiB
JavaScript
54 lines
1.2 KiB
JavaScript
// src/services/websocket.js
|
|
let ws = null;
|
|
let reconnectTimer = null;
|
|
|
|
export const connectWebSocket = (port = 8000) => {
|
|
// 关闭已有连接
|
|
if (ws) ws.close();
|
|
|
|
// 创建新连接
|
|
ws = new WebSocket(`ws://localhost:${port}`);
|
|
|
|
// 连接事件处理
|
|
ws.onopen = () => {
|
|
console.log('WS connected');
|
|
clearInterval(reconnectTimer);
|
|
|
|
};
|
|
|
|
ws.onerror = (error) => {
|
|
console.error('WS error:', error);
|
|
handleReconnect();
|
|
};
|
|
|
|
ws.onclose = (event) => {
|
|
console.log('WS closed:', event.reason);
|
|
handleReconnect();
|
|
};
|
|
|
|
ws.onmessage = (event) => {
|
|
console.log(12312312, event.data)
|
|
if (event.data instanceof Blob) {
|
|
// createImageBitmap(event.data).then(img => {
|
|
// ctx.drawImage(img, 0, 0);
|
|
// });
|
|
}
|
|
};
|
|
|
|
return ws;
|
|
};
|
|
|
|
// 自动重连机制
|
|
const handleReconnect = () => {
|
|
clearInterval(reconnectTimer);
|
|
// reconnectTimer = setInterval(() => {
|
|
// connectWebSocket(8000);
|
|
// }, 3000);
|
|
};
|
|
|
|
// 发送控制指令
|
|
export const sendControl = (data) => {
|
|
if (ws?.readyState === WebSocket.OPEN) {
|
|
ws.send(JSON.stringify(data));
|
|
}
|
|
}; |