I have Node server ,This server creates a tcp socket connection with other side TCP server. I'm trying to pipe tcp data but when i was received a message for second time i got both the new message and the previous one(the first one) in the same stream. How can i fix this?
var net = require('net');
var HOST = '127.0.0.1'; // parameterize the IP of the Listen
var PORT = 6969; // TCP LISTEN port
net.createServer(function(sock) {
console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
sock.on('data', function(data) {
sock.write(data);
socket.pipe(socket);
});
sock.on('close', function(data) {
console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
});
}).listen(PORT, HOST);
I'm assuming you want to create an echo server.
So you have two options - either piping:
// [...]
net.createServer(function(sock) {
sock.pipe(sock);
}
// [...]
Or you subscribe data and manually write to the socket (which is the same as pipe)
// [...]
net.createServer(function(sock) {
sock.on('data', function(data) {
sock.write(data);
});
}
// [...]
With your current program, when someone sends data the first time you echo the data but also create a pipe connection which means next time the data is sent twice (as you described).
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.