mirror of
https://github.com/smallmain/cocos-enhance-kit.git
synced 2025-10-20 05:45:23 +00:00
[adapters] 增加对多线程 WebSocket 的支持
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
87
adapters/platforms/wechat/worker/ws.js
Normal file
87
adapters/platforms/wechat/worker/ws.js
Normal 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;
|
Reference in New Issue
Block a user