[英]How to close all websocket connections
I'm trying to close all websocket connections. 我正在尝试关闭所有websocket连接。 Unfortunately I get allways the error:
不幸的是我总是得到错误:
TypeError: s.close is not a function
TypeError:s.close不是函数
I am using javascript rarely, and I can't find the error... 我很少使用javascript,并且找不到错误...
var sockets = [];
function addClient() {
var socket = new WebSocket("ws://localhost:8080/WebsocketHome/notification");
socket.onmessage = function (event){
[...]
};
sockets.push(socket);
}
function removeAllClients(){
for(var s in sockets){
s.close();
}
}
for
gives you the keys (which are: array indices in this case), not the values; for
为您提供键(在这种情况下为:数组索引),而不是值; you need: 你需要:
for(s in sockets)
sockets[s].close();
incredible, but this code: 不可思议,但是这段代码:
function removeAllClients(){
for(var s in sockets){
s.close();
}
}
iterate over indexes. 遍历索引。 So I do it now in this way:
所以我现在以这种方式做:
function removeAllClients(){
sockets.forEach(function(s) {
s.close();
});
}
and it works. 而且有效。 I'm really surprised...
我真的很惊讶
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.