Reputation:
I'm trying to write a simple client-server program in Node.js where the client will enter 2 arguments (for example, user will type S 4
to get the value of the square root of 4) for a mathematical computation, send it to the server, and the server will return the answer. It works for the most part; however, when the server returns the answer, the client displays the answer and also displays the original input. Can anyone point out why this is happening?
server.js
var net = require('net');
var server= net.createServer(function(c) {
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.on('data', function(data) {
data = data.toString().split(" ");
var num = parseInt(data[1], 10);
switch (data[0]){
case 'S':
c.write(Math.sqrt(num).toString());
}
});
c.write('What would you like to do?\n');
c.write('(S) - Square root <arg>\n');
c.pipe(c);
});
server.listen(3000, function() {
console.log('server bound');
});
client.js
var net = require('net');
var num = 1;
var client = net.connect({port:3000}, function() {
console.log('client connected');
});
client.on('data', function(data) {
if (num == 1) {
console.log(data.toString());
process.stdin.resume();
process.stdin.once('data', function(input) {
client.write(input);
});
num++;
} else {
console.log("Server returned: " + data.toString() + "\n");
process.exit();
}
});
client.on('end', function() {
console.log('\nclient disconnected\n');
});
To clarify: when I input S 4
in the client, the result printed to the screen is Server returned: 2S 4
Upvotes: 1
Views: 4718