客户端以1分钟的间隔向tcp服务器(ip:54.168.66.136,端口:8589)发送数据。我在这台服务器上接收数据没问题。现在我想这样做,这个tcp服务器必须将数据发送到另一个 服务器(IP:54.165.75.176,端口:8125)。我应该在代码中更改什么?
//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 :(得分:2)
这里的问题是每次收到数据缓冲区时,都会尝试创建连接。因此,当您收到第一个数据包时,数据包将被转发。第二个数据包被击中时会出现真正的问题。它尝试再次与服务器建立连接,但它已经存在。你从未在
之后调用client.end()client.write(数据)
理想情况下,每次收到数据包时都不应创建连接。为什么不保持连接并继续转发数据包?我的建议是:
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);