添加websocket连接
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
let ws = null;
|
||||
|
||||
// WebSocket连接地址
|
||||
const WS_URL = "ws://localhost:3000";
|
||||
|
||||
// 建立WebSocket连接
|
||||
export function connectWebSocket(token, onMessage, onOpen, onClose, onError) {
|
||||
// 如果已经连接,就不重复连接
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
console.log("WebSocket已经连接");
|
||||
return;
|
||||
}
|
||||
|
||||
// 携带JWT token
|
||||
ws = new WebSocket(`${WS_URL}?token=${token}`);
|
||||
|
||||
// 连接成功
|
||||
ws.onopen = () => {
|
||||
console.log("WebSocket连接成功");
|
||||
|
||||
if (onOpen) {
|
||||
onOpen();
|
||||
}
|
||||
};
|
||||
|
||||
// 接收到服务器消息
|
||||
ws.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
console.log("收到WebSocket消息:", data);
|
||||
|
||||
if (onMessage) {
|
||||
onMessage(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("WebSocket消息解析失败:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// 连接关闭
|
||||
ws.onclose = () => {
|
||||
console.log("WebSocket连接关闭");
|
||||
|
||||
if (onClose) {
|
||||
onClose();
|
||||
}
|
||||
|
||||
ws = null;
|
||||
};
|
||||
|
||||
// 连接错误
|
||||
ws.onerror = (error) => {
|
||||
console.error("WebSocket连接错误:", error);
|
||||
|
||||
if (onError) {
|
||||
onError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 发送消息
|
||||
export function sendWebSocketMessage(data) {
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
||||
console.error("WebSocket没有连接");
|
||||
return;
|
||||
}
|
||||
|
||||
ws.send(JSON.stringify(data));
|
||||
}
|
||||
|
||||
// 关闭WebSocket
|
||||
export function closeWebSocket() {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
ws = null;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取当前WebSocket
|
||||
export function getWebSocket() {
|
||||
return ws;
|
||||
}
|
||||
Reference in New Issue
Block a user