Cannot send response to TCP client

Refresh

March 2019

Views

636 time

1

I have a TCP server with the following code:

// Start a TCP Server
require('net').createServer(function (socket) {

  // Handle incoming messages from clients.
  socket.on('data', function (data) {
    console.log("received:" + data);

    // Do something with the data
    //...

    // Send result to client
    socket.write('OK');          // Code added which make the server crash
  });
}).listen(10000);

Each time a client connects, the server retrieve the data from the socket and process it. This runs well if I do not try to send a response to the client.

If I add the 'socket.write("ok");' line of code I get the following error (seems like the socket is already closed ?):

"memoryUsage":{"rss":22474752,"heapTotal":16571136,"heapUsed":7168552}},"os":{"loadavg":[1.25634765625,1.111328125,1.00341796875],"uptime":185009},"trace":[{"column":11,"file":"net.js","function":"errnoException","line":884,"method":null,"native":false},{"column":19,"file":"net.js","function":"TCP.onread","line":539,"method":"onread","native":false}],"stack":["Error: read ECONNRESET"," at errnoException (net.js:884:11)"," at TCP.onread (net.js:539:19)"],"level":"error","message":"uncaughtException: read ECONNRESET","timestamp":"2013-09-10T14:11:29.354Z"}

Any idea of what is wrong ?

EDIT

I use the following ruby code to simulate a client, should I use a thread for each socket I open ?

...
# Send test data to server
[1,2,3,4,5].each do |data|
  puts "sending #{data}"
  s = TCPSocket.open(host, port)
  s.puts data 
end
Luc

1 answers

2

Your ruby client completes execution and exits after sending the message to your server. It does not expect any response from server so it does not wait. You only need to modify your client like so:

  s = TCPSocket.open(host, port)
  s.puts data 
  puts s.read(2) //wait for response

The read is blocking so client won't send next message until it receives something from server in the loop. To send data parallely you would have to a) use non-blocking I/O in ruby (don't know how) or b) wrap this around a wrapper that spawns a thread for each client.