如何在Socket.IO中模拟连接失败

6
我正在开发一个应用程序,客户端通过Socket.io连接到nodejs服务器并订阅各种事件。这些订阅相当复杂,无法使用Socket.IO的通道功能进行处理。
这意味着客户端需要跟踪其订阅,并在断开连接时可能需要重新订阅。不幸的是,我不太确定Socket.IO如何处理重新连接以及这对客户端有多透明。
所以问题来了:我该如何模拟连接失败并强制Socket.IO重新连接?

4
拔下以太网线并重新插入? - xavierm02
或者只是在关闭连接之前删除其中一侧的连接,以查看另一侧的反应。 - xavierm02
@xavierm02:那样做可以,但这不是你想在单元测试中采用的一种方法 :-) 那我如何“只删除”连接? - n3rd
你应该拥有某种创建对象的API,而且该对象必须以某种方式具有关闭方法。如果不使用该关闭方法删除对象,则可能会出现错误。如果一端出现错误,则另一端将得到所需的错误信息。 - xavierm02
不,我没有关闭方法,因为连接不打算关闭。即使我有,我也需要在Socket.IO级别上模拟这个,因为我希望Socket.IO可以自动重新连接。 - n3rd
2个回答

0

Socket.io 在你的 socket 对象 中提供了各种事件。实际上,通过阅读它们的 API,你可以找到各种工具。

在 stackoverflow 上看这个例子 Socket.IO handling disconnect event


-2

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

客户端:

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

就是这样。非常简单和直接。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接