我正在运行以下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
在这种情况下,TCP套接字是使用IPv4地址创建的。只能使用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的快速模块为给定端口创建单独的(IPv4和IPv6)套接字?
我想要一个解决方案,其中netstat的oputput与此类似:
# 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'));
});
第二次尝试:我尝试在同一端口上创建多个服务器,但是当他们想要在同一个端口上初始化时会发生冲突。
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'));
});
答案 0 :(得分:0)
它被称为双栈模式,它与平台配置有关。 Linux 操作系统允许您通过 net.ipv6.bindv6only sysctl 打开/关闭它。我猜 Windows 也有类似的东西。