Reputation: 9187
I'm trying to close all websocket connections. Unfortunately I get allways the error:
TypeError: s.close is not a function
I am using javascript rarely, and I can't find the error...
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();
}
}
Upvotes: 2
Views: 7853
Reputation: 9187
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...
Upvotes: 3
Reputation: 1063964
for
gives you the keys (which are: array indices in this case), not the values; you need:
for(s in sockets)
sockets[s].close();
Upvotes: 2