2014-09-28 76 views
0

我正在socket.io上工作,我是新來的。我試圖在n次嘗試重新連接後斷開連接。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

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

在這裏獲得正確的參數:https://github.com/Automattic/socket.io-client#managerurlstring-optsobject

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

是。它的工作正常,非常感謝.. @德爾馬 – 2014-09-29 06:10:21