socket尝试后,socket.io重新连接应该会中断

时间:2014-09-28 17:23:50

标签: node.js socket.io

我正在研究socket.io,我是新手。我试图重新连接n次尝试断开连接。

服务器端代码:        var io = require(' socket.io')。listen(4000);

  io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
   socket.on('my other event', function (data) {
     console.log(data);
   });
  });

客户端代码是:

  <script src="http://localhost:4000/socket.io/socket.io.js"></script>
    <script>
     //var max_reconnects, socket;

     var max_reconnects = 5;
      var socket = io.connect('http://localhost:4000',
          {'reconnection delay': 100,
           'max reconnection attempts': max_reconnects,
             'reconnection limit' : 10});

     socket.on('news', function (data) {
      console.log(data);
      socket.emit('my other event', { my: 'data' });
    });

           socket.on("reconnecting", function(delay, attempt) {
        console.log("attempting reconnect - " + attempt + "-->" + delay);
         if (delay === max_reconnects) {
          //return console.log("all reconnect attempts failed");
            //socket.disconnect();
            //socket.server.close();
            socket.emit('forceDisconnect');
            console.log("Limited end");
         }

       });

请指导我如何在尝试次数后终止重新连接活动。给定的代码无法正常工作。并且重新连接回叫尝试也是未定义的。请指导我

1 个答案:

答案 0 :(得分:1)

您使用的是socket.io&gt; = 1.0但是使用之前的示例(有一些更改)?

点击此处查看正确的参数:https://github.com/Automattic/socket.io-client#managerurlstring-optsobject

var socket = io.connect('http://localhost:4000',
      {'reconnectionDelay': 100,
       'reconnectionAttempts': max_reconnects});