在多个端口上运行node.js http服务器 [英] running node.js http server on multiple ports

查看:176
本文介绍了在多个端口上运行node.js http服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人帮我查一下如何在node.js中获取服务器套接字上下文,以便我知道请求来自我服务器上的哪个端口号。
我可以读取服务器端口,如果我请求使用http标头,但我希望它通过网络和类似套接字上下文,它告诉请求来自哪个端口号。

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.

以下是示例代码:

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


推荐答案

req object具有对底层节点套接字的引用。您可以轻松获取此信息,如下所示: http://nodejs.org/api/http.html#http_message_socket http://nodejs.org/api/net.html#net_socket_remoteaddress

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_socket and 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);
});

这篇关于在多个端口上运行node.js http服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆