我在 nodejs 应用程序中使用 ws Plugin 来实现 web-socket。
当我从客户端关闭 ws 连接时,应该调用 ws close 事件。它在本地工作,但不能在服务器上工作。
这是示例代码:
exports.Initialize = function (server, app) {
wss = new WebSocket.Server({
server
});
app.on('upgrade', wss.handleUpgrade);
setWsHeartbeat(wss, (ws, data, binary) => {
if (data === '{"kind":"ping"}') { // send pong if recieved a ping.
ws.send('{"kind":"pong"}');
}
});
wss.on('connection', function connection(ws, req) {
clients.push({
ws,
type: location.query.type
});
ws.on('message', function (response) {
});
ws.on('close', function (e, c, b, x) {
let index = clients.findIndex(x => x.ws === ws);
if (index > -1) {
clients.splice(index, 1);
}
});
ws.on('error', function (e) {
let index = clients.findIndex(x => x.ws === ws);
if (index > -1) {
clients.splice(index, 1);
}
});
});
};