I am just trying to learn some client-server basics and I'm almost there with what I'm trying to do. I am just sending the server some input and having it respond back to the client with the data it received. However, it works fine once I send the first piece of data but once I send another input the server responds with two instances of that same piece of data, and so on. How do I get around this?
Server:
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var server = net.createServer();
server.on('connection', function(sock) {
console.log('CONNECTED: ' sock.remoteAddress ':' sock.remotePort);
sock.on('data', function(data) {
console.log('DATA ' sock.remoteAddress ':' data);
// write back data received to the client
sock.write('You said "' data '"');
});
});
server.listen(PORT, HOST);
console.log('Server listening on ' HOST ':' PORT);
Client:
var net = require('net');
var readline = require('readline');
var HOST = '127.0.0.1';
var PORT = 6969;
const r1 = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' HOST ':' PORT);
// continue talkback
function waitForUserInput() {
r1.question("Enter some data you wish to send: ", function(data) {
if(data == "exit") {
r1.close();
} else {
// write input data to the server
client.write(data);
// receive what data server sends back to client
client.on('data', function(server_data) {
console.log('DATA: ' server_data);
});
setInterval(waitForUserInput, 1000);
}
});
}
waitForUserInput();
});
CodePudding user response:
You keep adding more and more client.on('data', ...)
handlers. Each time you call waitForUserInput()
, you end up adding another duplicate handler for the data
message. So, after calling waitForUserInput()
twice, you have two identical handlers for the data
message so when a new piece of data arrives, each of the two handlers gets called and the output in your console appears twice. One one piece of data arrives, but you have duplicate handlers that are listening for it.
You can either use .once()
instead of .one()
or you can move the handler listening for the incoming data outside of the function so it's just installed once and only once.
Incidentally, using setInterval()
here is also a problem for several reasons. You're creating a new interval timer every time you call waitForUserInput()
and there's no coordination between that and when the question is actually answered.