Mysterious ECONNREFUSED with net.connect in Node

Posted on

Hit a minor gotcha playing with Node on the Mac recently.

In an app I'm working on I'd set up a simple Lua repl you can telnet into and it works fine. I've got an idea for making an application specific repl using Node Webkit so I started to write simple node to connect to my application repl:

var net = require('net');

var port = 6502;
var host = 'localhost';

var socket = net.connect(port,host, function() {
    console.log("Sending data");

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

socket.on("error", function(err) {

Only it won't connect. The lua code is pretty simple and binds to localhost:6502 as well, it works fine with nc or telnet but no beans here. All I get back is a connection refused JSON packet

{ [Error: connect ECONNREFUSED]
syscall: 'connect' }

It turns out that the lua socket code I'm using will set up an IPV6 socket when I bind to 'localhost' while net.connect will try and connect via IPV4. Telent and NC don't care and just detects the type of connection to rightly use.

The solutions are either change the node code to bind to '::1', IPV6's localhost equivalent and connect via IPV6 or changed my server code so it binds to Both work and I went for the latter.

There's a lot of things at play here and I don't which one of the many components (if any) aren't playing sensibly. Should localhost always default to IPV6? Should net.connect try and establish an IPV6 connection if it can't make an IPV4 one? I dunno, I'm pretty new to this but it chewed up enough of my Sunday to want to write it down in case anyone else had the same woes :)


Posted on


It's important to me that I enjoy working on my home dev project. If you're doing stuff for fun well it should be fun. I know that sounds kind of obvious but it's something I missed in the past at times and kind of have a good handle on now. FIrst of all you have to know what you like, right now for me (and I am pretty phase) I really enjoy:

  • Quick turn around of development
  • Learning new stuff
  • Not having to repetitious work

Last night wasn't really like that, it took bit of slog but I think I have my dev env set up nicely now to deliver on fun factor a bit more :)

Javascript / Coffeescript

I've been enjoying playing with Javascript the last week or so. I wrote a little server in node.js and have now moved onto writing an editor for my game in it. And its been a lot of fun. Very fast to develop in, lots of great resources on the web to help you learn and for a dynamic language it's pretty nippy too.

The immediacy though, that's what I like best. Save your file, flip to the browser, refresh and your code is running. I love that, so quick and no horrendous compile / link times. There's even a debugger. Well there's lots of them but the one in Safari has given me break points and variable inspection. That's nice for a dynamic language.

There are some niggles though. Syntactically it's a bit shit. Being able to inline embed anonymous functions often leads to a lot of indentation. You can get stuff like this pretty quickly

$('#tilda').tilda(function(_line, _console) {  
  quakeConsole(_line).success( function(_response) {
     _response.response.forEach( function(str) {
Ooof, look at that nasty trailing brace and bracket storm! The code ties the input from a [JQuery][jquery] based quake style [console in the browser][jqueryterminal] to my game back end (yeah I know, how cool is that?). It uses jQuery to get the node with the console in, sets a callback for any input. Once it gets input quakeConsole sends it to the game and also talks a callback for any response and that callback sends it back to console object. You get a lot of that sort of ping ponging in this sort of work. It really hurts the eyes. It's not fun to type and maintain either. I kept getting it wrong. Some sort of syntactic sugaring for Javascript that got rid of that would be nice wouldn't it? Turns out I'm not the only moany, fussy idiot in the world who's brace averse which is probably why [Coffeescript][coffeescript] exists. So the above now looks like this:
$('#tilda').tilda ( _line, _console ) ->  
    quakeConsole(_line).success (_response ) ->
        _response.response.forEach (str) ->
            _console.echo str
A lot easier on the eyes, quicker to type and easier to maintain. Scope is defined by indention rather than bracing and have never really done Python this is my first time for that sort of thing. A bit intimidating but I'm used to that now. Some help in the [editor][sublime] has made that process a lot easier. [SublimeLinter][sublimelinter] has been really handy which after a bit of fiddling has real time linting support for a lot of languages. Very handy seeing schoolboy errors fussily being pointed out as I type :) There's a bunch of other things Coffeescript brings to the party. As well as Python Ruby seems to have been a big influence too which has made me feel nicely at home. It also makes doing anything a bit class like a lot less fiddly and prone to error. JS can do class based OO but it means a lot of pointless typing. Not any more. There's a few issues, the code you debug is different from the code you right and being new to all of this means I'm debugging quite a bit. That's not been too bad though as the mapping is fairly light and surprisingly easy to map in your head. It's made writing JS more fun for me and I also go to learn something new so result. It does mean a compile stage though and I didn't want to lose any of the immediacy I'd been enjoying so much. # Compiling! Yuck So I wanted to preserve my tight little dev cycle of save in the editor, tab to the browser and immediately try things out. My home project has a nice build environment based around the excellent [Rake][rake] where any data that needs transforming to another format for use in the game is processed there. It only builds files that have changed is pretty quick but even adding that one extra step of invoking a build before trying out my new code rankled a bit. Turns out something called [Guard][guard] is a great solution for this. It's written in Ruby and easily installed as a Gem. Basically it'll sit in the background watching your files and as soon as any of them changes will do some background task for you. Best of all it's really popular and people have written a shed load of different plug ins that support all manner of different actions. And there's one for Rake. With Guard and the rake plug in installed all it needed was a Guardfile that listing out what files to watch and some options for rake to do its magic:
# A sample Guardfile

guard 'rake', :task =>; 'html' do  

Simples. A regex saying look at the html src dir and if anything changes? Builld the 'html' target with Rake. It works really really well. I have an immediacy of development that's an absolute joy while being able to use a pre-processed version of Javascript that I'm finding a lot less laborious to write. I've used the same setup to let me edit my CSS in sass as well.

Summing Up

It was a bit sloggy last night but it all feels really good now I have this all nicely in place. Something that's been great using technologies that have come from the web is there's a wealth of well maintained and incredibly useful tools.

Generally if there's something that niggles or your dev cycle seems a bit tortuous then someone has had a crack at solving that problem already. As with most things you need to put a bit of back into researching the issue and finding the right way forward. Chances are there's actually 10 solutions and half of them are shit but put in the effort, embrace the fear of the new and you'll likely find the solution you're looking for.


jquery jqueryterminal coffeescript sublimelinter sublime guard rake guardrake sass