Listen and request from the same port in node.js

I am testing the XML-RPC configured in node.js and would like to test the server that receives calls and responses, as well as the client that makes calls to the server and receive the response in the same node session, If I ran 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 an error:

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

While the above code will work if it is split into two files and runs as a separate node instance, is there a way to make the above work on the same node instance?

+3
source share
2 answers

, http- , . 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()
});
+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);
-1

All Articles