【问题标题】:Listen and request from same port in node.js从 node.js 中的同一端口侦听和请求
【发布时间】:2012-01-08 04:58:40
【问题描述】:

我正在测试在 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()

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

【问题讨论】:

    标签: http node.js


    【解决方案1】:

    正如上面提到的,您的 http-server 在您发出请求时可能没有运行。使用setTimeout 是完全错误。改用listen方法中的回调参数:

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

    【讨论】:

      【解决方案2】:

      当您向它发出请求时,您的 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);
      

      【讨论】:

        猜你喜欢
        • 2011-02-18
        • 1970-01-01
        • 2014-08-03
        • 2016-04-20
        • 1970-01-01
        • 1970-01-01
        • 2015-09-23
        • 2013-01-16
        • 1970-01-01
        相关资源
        最近更新 更多