简体   繁体   中英

Client sends data to tcp server and tcp server sends data to another server

client is sending data to tcp server(ip:54.168.66.136,port:8589)on 1 minute interval.I am receiving data on this server is fine. Now I want to do that this tcp server has to send data to another server(ip:54.165.75.176,port:8125). What should I change in my code?

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

The problem here is that every time you receive a data buffer, you try to create a connection. So when you receive the first packet, the packet is forwarded. The real problem comes when the second packet is hit. It tries to create a connection with the server again but it already exists. You never called client.end() after

client.write(data)

Ideally you shouldn't create a connection every time you receive a packet. Why not keep it connected and keep forwarding the packets? What I am suggesting is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM