サーバー全体を閉じずにサーバーからのWebSocket接続を終了することは可能ですか?もしそうなら、どうすればそれを達成できますか?
注:私はNodeJSをバックエンドおよび「ws」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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加