您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何终止WebSocket连接?

如何终止WebSocket连接?

如果要踢所有客户端而不关闭服务器,则可以执行以下操作:

for(const client of wss.clients)
{
  client.close();
}

wss.clients如果您要特别寻找一个,也可以进行过滤。如果您要踢客户端作为连接逻辑的一部分(即,它发送错误的数据等),则可以执行以下操作:

let WebSocketServer = require("ws").Server;
let wss = new WebSocketServer ({ port: 8080 });

wss.on('connection', function connection(ws) {
    ws.send('something');
    ws.close(); // <- this closes the connection from the server
});

一个基本的客户

"use strict";
const WebSocket = require("ws");
let ws = new WebSocket("ws://localhost:8080");
ws.onopen = () => {
    console.log("opened");
};
ws.onmessage = (m) => {
    console.log(m.data);
};
ws.onclose = () => {
    console.log("closed");
};

你会得到:

d:/example/node client
opened
something
closed
其他 2022/1/1 18:20:38 有364人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶