Paulo Mendonça
Paulo Mendonça

Reputation: 643

socket.io, How do i know if a socket remains active?

I'm giving my firsts steps on node and writing a simple chat app. Every time that nodejs gets a new socket connection it's saved in a simple array... My problem is when a connection is closed, because his reference remains there... How do i check if a connection is alive before emit any event to her, avoiding crashes?

Upvotes: 1

Views: 3845

Answers (1)

film42
film42

Reputation: 1095

I'm going to use an example from socket.io website.

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {
  var tweets = setInterval(function () {
    getBieberTweet(function (tweet) {
      socket.volatile.emit('bieber tweet', tweet);
    });
  }, 100);

  socket.on('disconnect', function () {
    clearInterval(tweets);
  });
});

On connect it passes a socket variable. This is unique to each client, that's why socket.emit sends to one client only, or why broadcast will send to everyone except the sender.

socket.on('disconnect', function () {
  clearInterval(tweets);
});

Notice how it clears the interval? Again this is client specific because it's happening to a specific "socket" so you can do something like:

socket.on('disconnect', function () {
  socket.broadcast.emit('disconnected', {user: "film42", status: "disconnected from server"});
});

Socket.IO will handle the heartbeat / disconnecting gracefully so you don't need to worry about the extras, just handling the disconnect. I hope that works for you :).

Upvotes: 4

Related Questions