[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

@@ -9,3 +9,8 @@ if (CC_WORKER_AUDIO_SYSTEM) {
ipcMain.registerHandler("audioAdapter", audioWorkerAdapter);
}
}
if (CC_WORKER_WEBSOCKET) {
const wsWorkerAdapter = require("./ws.js");
ipcMain.registerHandler("wsAdapter", wsWorkerAdapter);
}

View File

@@ -0,0 +1,87 @@
let _id = 0;
class WorkerWebSocket {
id = _id++;
onopen = null;
onclose = null;
onerror = null;
onmessage = null;
constructor(url, protocols) {
wsWorkerAdapter.register(this);
worker.ws.connectSocket([this.id, url, protocols]);
}
onOpen(cb) {
this.onopen = cb;
}
onMessage(cb) {
this.onmessage = cb;
}
onClose(cb) {
this.onclose = cb;
}
onError(cb) {
this.onerror = cb;
}
send(res) {
worker.ws.send([this.id, res.data]);
}
close(res) {
worker.ws.close([this.id, res.code, res.reason]);
}
}
var wsWorkerAdapter = {
sockets: {},
register(socket) {
this.sockets[socket.id] = socket;
},
onOpen(args, cmdId, callback) {
const id = args[0];
const ws = this.sockets[id];
if (ws) {
ws.onopen?.();
}
},
onMessage(args, cmdId, callback) {
const id = args[0];
const data = args[1];
const ws = this.sockets[id];
if (ws) {
ws.onmessage?.({ data });
}
},
onClose(args, cmdId, callback) {
const id = args[0];
const data = args[1];
const ws = this.sockets[id];
if (ws) {
ws.onclose?.(data);
delete this.sockets[id];
}
},
onError(args, cmdId, callback) {
const id = args[0];
const data = args[1];
const ws = this.sockets[id];
if (ws) {
ws.onerror?.(data);
delete this.sockets[id];
}
},
};
globalThis.WorkerWebSocket = WorkerWebSocket;
module.exports = wsWorkerAdapter;