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