2017-08-17 279 views
-1

客戶端正在以1分鐘的時間間隔向tcp服務器(ip:54.168.66.136,端口:8589)發送數據。我在此服務器上接收數據很好。現在我想要做的是,此tcp服務器必須將數據發送到另一個 服務器(ip:54.165.75.176,端口:8125)。我應該在代碼中更改哪些內容?客戶端向tcp服務器發送數據,tcp服務器向另一臺服務器發送數據

//tcpserver.js code is below 
net = require('net'); 
var http = require('http'); 
var moment = require('moment'); 
var fs = require('fs'); 
var clients = []; 
var client = new net.Socket(); 
var querystring = require('querystring'); 
net.createServer(function (socket) { 
clients.push(socket); 
socket.connected_state = "IGN_ON"; 
socket.on('data', function (data) { 

try { 
    data =""+data; 
    client.connect(8125, '54.165.75.176', function() { 
      client.write(data); 
    }); 
    /*client.on('close', function() { 
    // console.log('Connection closed'); 
    });*/ 
    }catch (err) { 
    } 
    }); 
    socket.on('end', function() { 
        clients.splice(clients.indexOf(socket), 1); 
    }); 

}).listen(8589); 
+0

的https://stackoverflow.com/q/45636340/207421 – EJP

+0

stackoverflow.com/q/45636340/207421問題完全重複的客戶端編碼 –

回答

1

這裏的問題是,每次您收到數據緩衝區時,都會嘗試創建連接。所以當你收到第一個數據包時,數據包就會被轉發。當第二個數據包被擊中時,真正的問題就出現了。它試圖再次創建與服務器的連接,但它已經存在。後

client.write(數據)你從沒叫過client.end()

理想情況下,你不應該創建每次收到一個數據包時的連接。爲什麼不保持連接並繼續轉發數據包?我的建議是:

net = require('net'); 
var http = require('http'); 
var moment = require('moment'); 
var fs = require('fs'); 
var clients = []; 
var client = new net.Socket(); 
var querystring = require('querystring'); 

client.connect(8125, '54.165.75.176', function() { 
       console.log('Connected to Server: 54.165.75.176'); 
     }); 

net.createServer(function (socket) { 
    clients.push(socket); 
    socket.connected_state = "IGN_ON"; 
    socket.on('data', function (data) { 

     try { 
      data =""+data; 
      client.write(data); 
      /*client.on('close', function() { 
      // console.log('Connection closed'); 
      });*/ 
     } 

     catch (err) { 
     } 
    }); 

    socket.on('end', function() { 
     clients.splice(clients.indexOf(socket), 1); 
    }); 
}).listen(8589); 
+0

感謝亞爾終於解決了 –

+0

快樂幫助 :) – WinningAddicted

相關問題