[adapters] 增加对多线程 WebSocket 的支持

This commit is contained in:
SmallMain
2024-11-29 10:26:50 +08:00
parent 8b254fb84d
commit 203e5e290f
5 changed files with 166 additions and 7 deletions

View File

@@ -14,3 +14,8 @@ if (globalThis.CC_WORKER_HTTP_REQUEST) {
const http = require("./http-worker.js");
registerHandler("http", http);
}
if (globalThis.CC_WORKER_WEBSOCKET) {
const ws = require("./ws-worker.js");
registerHandler("ws", ws);
}

View File

@@ -0,0 +1,58 @@
const { main } = require("./ipc-worker.js");
var ws_worker = {
sockets: {},
connectSocket(id, url, protocols) {
try {
const ws = worker.connectSocket({
url,
protocols,
tcpNoDelay: true,
});
this.sockets[id] = ws;
ws.onOpen(() => {
main.wsAdapter.onOpen(id);
});
ws.onMessage(res => {
main.wsAdapter.onMessage(id, hookWSRecv ? hookWSRecv(res.data) : res.data);
});
ws.onError(res => {
delete this.sockets[id];
main.wsAdapter.onError(id, res);
});
ws.onClose(res => {
delete this.sockets[id];
main.wsAdapter.onClose(id, res);
});
} catch (error) {
main.wsAdapter.onError(id, { errMsg: String(error) });
}
},
send(id, data) {
const ws = this.sockets[id];
if (ws) {
ws.send({
data: hookWSSend ? hookWSSend(data) : data,
});
}
},
close(id, code, reason) {
const ws = this.sockets[id];
if (ws) {
ws.close({
code,
reason,
});
}
},
};
module.exports = ws_worker;