2011-05-03 60 views
3

我正在測試node.js中設置的XML-RPC,並且想要測試接收調用和響應的服務器以及調用服務器和接收響應在同一節點中的會話。如果我運行http.createServer和http.request用相同的主機和端口,我得到:從node.js中的同一端口收聽和請求

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

測試代碼,將產生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') 
}).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() 

雖然代碼,如果上面的分離工作會爲兩個文件並運行作爲單獨的節點的情況下,有沒有辦法讓上面在同一個節點實例上運行?

回答

1

由於這是上面的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);