javascript 在多个端口上运行 node.js http 服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19296797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
running node.js http server on multiple ports
提问by Anuradha Singh
Please can anybody help me to find out how to get the server socket context in node.js, so that i will come to know request came on which port number on my server. I can read the server port if i request using http headers but I want it through network and something like socket context which tells request came on which port number.
请任何人都可以帮助我找出如何在 node.js 中获取服务器套接字上下文,以便我知道请求来自我服务器上的哪个端口号。如果我使用 http 标头请求,我可以读取服务器端口,但我希望它通过网络和诸如套接字上下文之类的东西来告诉请求来自哪个端口号。
Here is the sample code:
这是示例代码:
var http=require('http');
var url = require('url');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
var serPort=req.headers.host.split(":");
console.log("PORT:"+serPort[1]);//here i get it using http header.
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});
回答by Tim Caswell
The req
object has a reference to the underlying node socket. You can easily get this information as documented at: http://nodejs.org/api/http.html#http_message_socketand http://nodejs.org/api/net.html#net_socket_remoteaddress
该req
对象具有对底层节点套接字的引用。您可以轻松获取此信息,如在以下位置记录的:http: //nodejs.org/api/http.html#http_message_socket和http://nodejs.org/api/net.html#net_socket_remoteaddress
Here is your sample code modified to show the local and remote socket address information.
这是您修改后的示例代码以显示本地和远程套接字地址信息。
var http=require('http');
var ports = [7006, 7007, 7008, 7009];
var servers = [];
var s;
function reqHandler(req, res) {
console.log({
remoteAddress: req.socket.remoteAddress,
remotePort: req.socket.remotePort,
localAddress: req.socket.localAddress,
localPort: req.socket.localPort,
});
}
ports.forEach(function(port) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
});