0

I have this example from https://nodejs.org that echoes back the input.

var net = require('net');

var server = net.createServer(function (socket) {
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

server.listen(1338, 'localhost');

I used this ruby script to send a data:

require 'socket'
a = TCPSocket.new('localhost', 1338) # could replace 127.0.0.1 with your "real" IP if desired.
a.write "hi server!"
puts "got back:" + a.recv(1024)
a.close

However, I got this error

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: read ECONNRESET
    at exports._errnoException (util.js:746:11)
    at TCP.onread (net.js:550:26)

What might be wrong? When I just use socket.end(), it just works fine.

var net = require('net');
var server = net.createServer(function (socket) {
    console.log("Connection from " + socket.remoteAddress);
    socket.end("Hello World\n");

});
server.listen(1338, "localhost");

ADDED

I needed to modify the ruby code not to cause an error with nodejs.

require 'socket'
a = TCPSocket.new('localhost', 1338) # could replace 127.0.0.1 with your "real" IP if desired.
a.write "hi server!"
puts "got back:" + a.recv(1024)
puts "got back:" + a.recv(1024)
a.close

1 Answer 1

3

Your Ruby script is closing the connection prematurely (before reading all the data).

Your Node.js code should anticipate this possibility and handle it:

var server = net.createServer(function (socket) {
  socket.on('error', function(err) {
    console.error('SOCKET ERROR:', err);
  });
  socket.write('Echo server\r\n');
  socket.pipe(socket);
});

Here we’re doing nothing but logging the error, although you could do something else with it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.