添加websocket文件
This commit is contained in:
74
src/websocket.js
Normal file
74
src/websocket.js
Normal file
@@ -0,0 +1,74 @@
|
||||
// utils/websocket.js
|
||||
|
||||
let socket = null;
|
||||
let messageCallback = null;
|
||||
|
||||
/**
|
||||
* 连接 WebSocket
|
||||
* @param {String} url WebSocket 地址
|
||||
* @param {Function} onMessage 消息回调
|
||||
*/
|
||||
function connectWebSocket(token, onMessage) {
|
||||
messageCallback = onMessage;
|
||||
|
||||
socket = uni.connectSocket({
|
||||
url: `ws://120.79.241.5:8000/socket?authorization=${token}`,
|
||||
success: () => {
|
||||
console.log("连接建立成功");
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error("连接失败", err);
|
||||
},
|
||||
});
|
||||
|
||||
// 接收消息
|
||||
uni.onSocketMessage((res) => {
|
||||
if (messageCallback) {
|
||||
messageCallback(res.data);
|
||||
}
|
||||
});
|
||||
|
||||
// 错误处理
|
||||
uni.onSocketError((err) => {
|
||||
console.error("WebSocket 错误", err);
|
||||
});
|
||||
|
||||
// 关闭处理
|
||||
uni.onSocketClose(() => {
|
||||
console.log("WebSocket 已关闭");
|
||||
socket = null;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息
|
||||
* @param {String} msg 要发送的消息内容
|
||||
*/
|
||||
function sendWebSocketMessage(msg) {
|
||||
if (socket && uni.sendSocketMessage) {
|
||||
uni.sendSocketMessage({
|
||||
data: msg,
|
||||
fail: (err) => {
|
||||
console.error("发送消息失败", err);
|
||||
},
|
||||
});
|
||||
} else {
|
||||
console.warn("WebSocket 未连接");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭连接
|
||||
*/
|
||||
function closeWebSocket() {
|
||||
if (socket) {
|
||||
uni.closeSocket();
|
||||
socket = null;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
connectWebSocket,
|
||||
sendWebSocketMessage,
|
||||
closeWebSocket,
|
||||
};
|
||||
Reference in New Issue
Block a user