Created
October 9, 2011 00:37
-
-
Save neerolyte/1273113 to your computer and use it in GitHub Desktop.
Connections back to the same thread...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
}); | |
}); |
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
This code works fine for me on v0.4.7: