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();
}
}
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();
}
}
Share
Improve this question
edited Apr 28, 2015 at 10:10
devops
asked Apr 28, 2015 at 10:04
devopsdevops
9,2036 gold badges50 silver badges77 bronze badges
3
-
it it possible that somewhere you have something else being pushed into the array? if you just look at
sockets
in the console window: what does it contain? – Marc Gravell Commented Apr 28, 2015 at 10:06 -
hm
console.log('s: ' + s)
prints s: 0, s: 1, s: 2, ... – devops Commented Apr 28, 2015 at 10:09 -
It seems your
sockets.push(socket);
is pushing something else than a socket. Before you push it,console.log
it. – vaso123 Commented Apr 28, 2015 at 10:12
2 Answers
Reset to default 3incredible, 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...
for
gives you the keys (which are: array indices in this case), not the values; you need:
for(s in sockets)
sockets[s].close();