开发者

Listen and request from same port in node.js

I am testing an XML-RPC set up in node.js and would like to test the server receiving calls and responding as well as the client making calls to the server and receiving a response in the same node session. If I run http.createServer and http.request with the same host and port, I get:

Error: ECONNREFUSED, Connection refused
at Socket._onConnect (net.js:600:18)
at IOWatcher.onWritable [as callback] (net.js:186:12)

Test code that will generate the errror:

var http = require('http')

var options = {
  host: 'localhost'
, port: 8000
}

// Set up server and start listening
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('success')
}).l开发者_C百科isten(options.port, options.host)

// Client call
// Gets Error: ECONNREFUSED, Connection refused
var clientRequest = http.request(options, function(res) {
  res.on('data', function (chunk) {
    console.log('Called')
  })
})

clientRequest.write('')
clientRequest.end()

While the code above will work if separated into two files and run as separate node instances, is there a way to get the above to run on the same node instance?


As it was mentioned above your http-server may not be running at the time you make a request. Using setTimeout is completely wrong. Use the callback parameter in listen method instead:

var http = require('http')

var options = {
  host: 'localhost'
, port: 8000
}

// Set up server and start listening
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('success')
}).listen(options.port, options.host, function() {
  // Client call
  // No error, server is listening
  var clientRequest = http.request(options, function(res) {
    res.on('data', function (chunk) {
      console.log('Called')
    })
  })

  clientRequest.write('')
  clientRequest.end()
});


Your HTTP server probably isn't fully loaded and operational at the time when you are doing your request to it. Try wrap your client request with setTimeout to give your server a time to set up, for example like this:

var http = require('http')

var options = {
  host: 'localhost'
, port: 8000
}

// Set up server and start listening
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.end('success')
}).listen(options.port, options.host)

setTimeout(function() {
    // Client call
    // Shouldn't get error
    var clientRequest = http.request(options, function(res) {
      res.on('data', function (chunk) {
        console.log('Called')
      })
    })

    clientRequest.write('')
    clientRequest.end()
}, 5000);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜