Reputation: 379
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:
Upvotes: 4
Views: 3900
Reputation: 379
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:
All fixed now though :)
gaz
Upvotes: 4
Reputation: 269
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.
Upvotes: 0
Reputation: 533
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);
Upvotes: 0