最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to close all websocket connections - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 3

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...

for gives you the keys (which are: array indices in this case), not the values; you need:

for(s in sockets)
    sockets[s].close();
发布评论

评论列表(0)

  1. 暂无评论