如何终止WebSocket连接? [英] How to terminate a WebSocket connection?

查看:137
本文介绍了如何终止WebSocket连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在不关闭整个服务器的情况下终止服务器的Websocket连接?如果是这样,我该如何实现?

Is it possible to terminate a websocket connection from server without closing the entire server? If it is then, how can I achieve it?

注意:我正在使用NodeJS作为后端和'ws'Websocket模块.

Note: I'm using NodeJS as back-end and 'ws' websocket module.

推荐答案

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

If you want to kick ALL clients without closing the server you can do this:

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

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

you can also filter wss.clients too if you want to look for one in particular. If you want to kick a client as part of the connection logic (i.e. it sends bad data etc), you can do this:

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

这篇关于如何终止WebSocket连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆