开发者

How to simulate a connection failure in Socket.IO

I'm developing an appl开发者_如何学运维ication where clients connect to a nodejs server via Socket.io and subscribe to a variety of events. These subscriptions are fairly complex can not be handled with Socket.IO's channel feature.

This means that the client needs to keep track of its subscriptions and may have to re-subscribe when it was disconnected. Unfortunately, I'm not quite sure how Socket.IO handles reconnecting and exactly how transparent that happens to the client.

So here's the question: how can I simulate a connection failure and force Socket.IO to reconnect?


Socket.io is providing you events in your socket object. Actually, you can find various tools by reading their API.

See this exemple on stackoverflow Socket.IO handling disconnect event


From my experience, I found this to be the easiest and useful solution:

Client side:

// the next 3 functions will be fired automatically on a disconnect.
// the disconnect (the first function) is not required, but you know, 
// you can use it make some other good stuff.

socket.on("disconnect", function() {
  console.log("Disconnected");
});

socket.on("reconnect", function() {
  // do not rejoin from here, since the socket.id token and/or rooms are still
  // not available.
  console.log("Reconnecting");
});

socket.on("connect", function() {
  // thats the key line, now register to the room you want.
  // info about the required rooms (if its not as simple as my 
  // example) could easily be reached via a DB connection. It worth it.
  socket.emit("registerToRoom", $scope.user.phone);
});

Server side:

io.on('connection', function(socket){
  socket.on("registerToRoom", function(userPhone) {   
    socket.join(userPhone);   
  });
});

And thats it. Very simple and straight forward.

You also can add in the connected socket (the last function) some more updates to the user display, such as refreshing its index or something else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜