2011-08-29 81 views
5

我正在开发一个应用程序,其中客户端通过Socket.io连接到nodejs服务器并订阅各种事件。这些订阅相当复杂,无法使用Socket.IO的通道功能处理。如何模拟Socket.IO中的连接故障

这意味着客户端需要跟踪其订阅,并且在断开连接时可能必须重新订阅。不幸的是,我不太确定Socket.IO如何处理重新连接,以及客户端发生的透明度如何。

所以,这里的问题是:如何模拟连接失败并强制Socket.IO重新连接?

+3

拔下以太网电缆并重新插入? – xavierm02

+0

或者,也许只是先删除任何一方的连接,然后再关闭它,以查看对方的反应。 – xavierm02

+0

@ xavierm02:这可行,但真的不是你想在单元测试中使用的方法:-)我该如何“删除”连接? – n3rd

回答

-1

本例从我的经验,我发现这是最简单的和有用的解决方案:

客户端:

// 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); 
}); 

服务器端:

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

而那就是它。非常简单直接。

您还可以在连接的套接字(最后一个功能)中添加更多用户显示更新,例如刷新其索引或其他内容。