Bren
Bren

Reputation: 3696

How/should one remove old websocket connections?

I'm using 'ws' on Node.js and I'm not really sure how old connections are removed (old connections being disconnects or idle ones, this may be two different issues). Do I need to implement this manually for the two types?

Upvotes: 2

Views: 3024

Answers (1)

For this you need to first maintain a list of live web socket connection objects in your server end. When the user disconnects from web socket by closing the browser or any other means you need to delete the user web socket connection object from the list.

Server side codes. You can refer to members array in the following code for handling this.

io.on("connection",function(client)
{
  client.on("join",function(data)
  {
    members[membercount] = client;
    membername[membercount] = data;
    membercount++;
    for(var i =0 ;i <members.length;i++)
    {
      members[i].emit("message",membername);
    }
  });
  client.on("messages",function(data)
  {
    for(var i =0 ;i <members.length;i++)
    {
      if(members[i].id !== client.id)
      {
        members[i].emit("message",data);
      }
    }
  });
  client.on("disconnect",function(data)
  {
    for(var i =0;i<members.length;i++)
    {
      if(members[i].id ===  client.id )
      {
        membercount--;
        members.splice(i,1);
        membername.splice(i,1);
      }
    }
    for(var i =0 ;i <members.length;i++)
    {
      members[i].emit("message",membername);
    }
  });
});

Hope this helps !!!!!

Upvotes: 1

Related Questions