如何使用NodeJS中的http模块在同一端口上打开IPv4和IPv6套接字?

我正在运行以下的NodeJS服务器代码:

var express = require('express'); var path = require('path'); var fs = require('fs'); var bodyParser = require('body-parser'); var http = require('http'); var ejs = require('ejs'); var app = express(); //configure the app app.set('port', process.env.PORT || 3000); // set the view engine to ejs app.set('view engine', 'ejs'); app.use(bodyParser.raw()); app.use(bodyParser.urlencoded({ extended: true })); app.use(function(req, res, next) { res.set('Access-Control-Allow-Origin', 'https://myServer.com'); res.set('Access-Control-Allow-Methods', 'GET, OPTIONS,POST, PUT, PATCH, DELETE'); res.set('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); res.set('Access-Control-Allow-Credentials', true); next(); }); //assets require(path.join(__dirname, './server.js')).Server(app); 

使用IPv4地址对服务器进行参数化时:

 var server = http.createServer(app); //create server server.listen(app.get('port'), "0.0.0.0", function() { var host = server.address().address; console.log('mockserver listening on host:' + host + ":" + app.get('port')); }); 

Netstat提供以下输出:

 # netstat -plnt | grep node tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN 1234/node /local/op 

在这种情况下,使用IPv4地址创buildTCP套接字。 该服务只能使用IPv4地址访问。

使用IPv6地址对服务器进行参数化时:

 var server = http.createServer(app); //create server server.listen(app.get('port'), "::", function() { var host = server.address().address; console.log('mockserver listening on host:' + host + ":" + app.get('port')); }); 

netstat给出了这个输出:

 # netstat -plnt | grep node tcp6 0 0 :::3000 :::* LISTEN 1234/node /local/op 

并且可以使用IPv4和IPv6地址来访问该服务。 (可能是模拟IPv4的内核选项打开)

问题 :是否可以使用NodeJS的express模块​​为给定端口创build单独的(IPv4和IPv6)套接字?

我想要一个netstat的oputput类似于这个的解决scheme:

 # netstat -plnt | grep node tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN 1234/node /local/op tcp6 0 0 :::3000 :::* LISTEN 1234/node /local/op 

尝试 :我尝试了以下尝试,这是不工作的:

第一次尝试:我试图用一台服务器打开多个套接字,但是listen函数的参数化可能与我所想象的不同。

 server.listen(app.get('port'), ["0.0.0.0", "::0"], function() { console.log('EEA-mockserver server listening on host:' + app.get('port')); }); 

要么

 server.listen(app.get('port'), "0.0.0.0", "::0", function() { console.log('EEA-mockserver server listening on host:' + app.get('port')); }); 

第二次尝试:我试图在同一个端口上创build多个服务器,但是当他们想通过同一个端口初始化它们时会发生冲突。

 var server4 = http.createServer(app); var server6 = http.createServer(app); server4.listen(app.get('port'), "0.0.0.0", function() { var host = server4.address().address; console.log('EEA-mockserver server listening on host:' + host + ":" + app.get('port')); }); server6.listen(app.get('port'), "::", function() { var host = server6.address().address; console.log('EEA-mockserver server listening on host:' + host + ":" + app.get('port')); }); 

Solutions Collecting From Web of "如何使用NodeJS中的http模块在同一端口上打开IPv4和IPv6套接字?"