2017-12-08 13 views
0

現在、デバイス(TCPソケット)に繰り返し接続して切断しようとしています。ここでは、デバイス Node.JS rawソケット:繰り返しの接続切断を行う方法?

  • への流れ

    1. Connectの "データ" を送信しています。
    2. もう一方の端がデータを受信し、すでに応答していることを確認するために200msecの遅延があります。
    3. データを処理します。
    4. 接続を切断します。現在

      var net = require('net'); 
      var HOST = '127.0.0.1'; 
      var PORT = 23; 
      
      // (a) ========= 
      var client = new net.Socket(); 
      client.connect(PORT, HOST, function() { 
      
          console.log('CONNECTED TO: ' + HOST + ':' + PORT); 
          // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client 
          client.write('data'); 
      
      }); 
      
      // Add a 'data' event handler for the client socket 
      // data is what the server sent to this socket 
      client.on('data', function(data) { 
      
          console.log('DATA: ' + data); 
          // Close the client socket completely 
          client.destroy(); 
      }); 
      
      // Add a 'close' event handler for the client socket 
      client.on('close', function() { 
          console.log('Connection closed'); 
      }); 
      
      // (b) ========= 
      

      、上記のコード:

    5. 待ち1秒
    6. 行くためのバックこの1回限りの接続コードは(私はウェブからそれを得た)働いている

    1.へ1回の接続で動作します。私はコードを(a)から(b)をwhile(true)ループに入れて、最後にhttps://www.npmjs.com/package/sleepを使用して1秒のスリープ状態にしました。接続がそのセットアップで実行されていないようです。

    これについてのご意見は参考になります。

  • 答えて

    2

    私はこれを行うための最善の方法だと思いますが、あなたが機能「loopConnection」で何をしたいのかencapsule、このような各client.on('close')に再帰的に呼び出すことです:

    var net = require('net'); 
    var HOST = '127.0.0.1'; 
    var PORT = 23; 
    
    var loopConnection = function() { 
        var client = new net.Socket(); 
    
        client.connect(PORT, HOST, function() { 
         console.log('CONNECTED TO: ' + HOST + ':' + PORT); 
         client.write('data'); 
        }); 
    
        client.on('data', function(data) { 
         console.log('DATA: ' + data); 
         client.destroy(); 
        }); 
    
        client.on('close', function() { 
         console.log('Connection closed'); 
         setTimeout(function() { 
          loopConnection(); // restart again 
         }, 1000); // Wait for one second 
        }); 
    }; 
    
    loopConnection(); // Initialize and first call loopConnection 
    

    それがお役に立てば幸いです。

    +1

    それが機能しました!どうもありがとうございます!!!!!!! –

    関連する問題