从node.js中的同一端口监听和请求

时间:2011-05-03 06:38:39

标签: http node.js

我正在测试在node.js中设置的XML-RPC,并且希望测试接收调用和响应的服务器以及调用服务器并在同一节点会话中接收响应的客户端。如果我使用相同的主机和端口运行http.createServer和http.request,我得到:

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

测试将生成错误的代码:

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)

// 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()

虽然上面的代码如果分成两个文件并作为单独的节点实例运行,但是有没有办法让上面的代码在同一节点实例上运行?

2 个答案:

答案 0 :(得分:1)

如上所述,您的http服务器可能在您提出请求时未运行。使用setTimeout完全错误。请改用listen方法中的callback参数:

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()
});

答案 1 :(得分:-1)

您的HTTP服务器可能在您向其发出请求时未完全加载并且可以正常运行。尝试使用setTimeout包装您的客户端请求,以便为您的服务器设置一个时间,例如:

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);