我已经在nodejs应用程序中使用了ws插件来实现网络套接字。
当我从客户端关闭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);
}
});
});
};