Question

I have a telnet server embedded in a C++ app that I can connect to with no problem using telnet.

I want to write a node application that will connect to my server and I have tried this

var net = require('net');

var port = 6502
var host = '127.0.0.1'

var socket = net.connect(port,host, function() {
    console.log("Sending data");
    socket.write("hello\r\n")

    socket.on("data", function (data) {
        console.log("received data");
        console.log( data.toString() );
        socket.end();
    })
})

socket.on("error", function(err) {
    console.log("Error");
    console.log(err);
})

Unfortunately what I get back is this

> node test.js
{ [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

What's really odd is if I set up a simple echo server with node everything works fine. Here's the working echo server code:

var net = require('net');

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

server.listen(6502, '127.0.0.1');

and from that I get

Sending data
received data
Echo server
hello

Is there any reason why:

  • I can telnet into my app fine
  • I can connect from node to my node echo server on the same port
  • I get a connection refused if I connect from my node app to my app

Extra Info

  • On OSX (mavericks)
  • Node version 0.10.28
  • Telnet server in C++ is provided via embedded lua and luasocket (lua 5.1)
Was it helpful?

Solution

Solved!

The issue is the code in my app server was binding to localhost and by default that binds to the IPV6 address of ::1

Passing a host of localhost to net.connect assumes IPV4 and doesn't work.

The mac command line telnet and nc both work fine with this and connect correctly.

Two solutions:

  • App binds to 127.0.0.1 and localhost in node works fine
  • Set host address to ::1 in test.js and it connects via ipv6

All fixed now though :)

gaz

OTHER TIPS

Looks like you forgot to tell the server to listen in your code. It throws a connection refused error because there is nothing to connect to...

Add this at the end: server.listen(port);

The prototype for net.connect is (options, callback) See http://nodejs.org/api/net.html#net_net_connect_options_connectionlistener

I would then suggest to test your code against a standard telnet server to see how it behaves, and finally I would strongly recommend the use of jshint or jslint.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top