Skip to content

Instantly share code, notes, and snippets.

@neerolyte
Created October 9, 2011 00:37
Show Gist options
  • Save neerolyte/1273113 to your computer and use it in GitHub Desktop.
Save neerolyte/1273113 to your computer and use it in GitHub Desktop.
Connections back to the same thread...
// Produces:
// Error: ECONNREFUSED, Connection refused
// at Client._onConnect (net.js:601:18)
// at IOWatcher.onWritable [as callback] (net.js:186:12)
var http = require('http')
var server = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello world\n');
});
server.listen(1337, "127.0.0.1");
var client = http.createClient(1337, '127.0.0.1');
var req = client.request('GET', '/', {});
req.end();
req.on('response', function(res) {
res.on('data', function(chunk) {
console.log(chunk);
});
});
@neerolyte
Copy link
Author

Weird that it works for you :p

My error was appearing under node v0.4.11 in Ubuntu 11.04 x86_64.

The correct solution pointed out to me on the mailing list was to utilise the callback in the server.listen call found here: http://nodejs.org/docs/v0.4.12/api/http.html#server.listen

The server.listen returns before it's guaranteed to have bound to the port. Seems like on my machine it was not bound and yours it is.

Here's something that's closer to right...

var http = require('http')

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello world\n');
});

server.listen(1337, "127.0.0.1", function() {
    var client = http.createClient(1337, '127.0.0.1');
    var req = client.request('GET', '/', {});

    req.end();
    req.on('response', function(res) {
        res.on('data', function(chunk) {
            if (!this.body) this.body = '';
            this.body += chunk;
        });
        res.on('end', function() {
            console.log(this.body);
            server.close();
        }); 
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment