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
4

1 回答 1

2

您的 ruby​​ 客户端在将消息发送到您的服务器后完成执行并退出。它不期望来自服务器的任何响应,因此它不会等待。您只需要像这样修改您的客户端:

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

读取被阻塞,因此客户端在循环中从服务器接收到某些内容之前不会发送下一条消息。要并行发送数据,您必须 a)在 ruby​​ 中使用非阻塞 I/O(不知道如何)或 b)将其包装在为每个客户端生成线程的包装器周围。

于 2013-09-10T15:23:12.383 回答