node生成的每个服务器必须分配一个端口。那么如果我们在工作中遇到一个需求:让同一个端口或地址既支持http协议又支持https协议,HTTP与HTTPS都属于应用层协议,所以只要我们在底层协议中进行反向代理,就可以解决这个问题!
var fs = require('fs'); // 引入文件&目录模块
var http = require('http'); // 引入http模块
var path = require('path'); // 引入路径模块
var https = require('https'); // 引入https模块
var net = require('net');
var httpport = 3000;
var httpsport = 3000;
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('secured hello world');
}).listen(httpport,'0.0.0.0',function(){
console.log('HTTP Server is running on: http://localhost:%s',httpport)
});
var options = {
pfx: fs.readFileSync(path.resolve(__dirname, 'config/server.pfx')),
passphrase: 'bhsoft'
};
var sserver = https.createServer(options, function(req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('secured hello world');
}).listen(httpsport,'0.0.0.0',function(){
console.log('HTTPS Server is running on: https://localhost:%s',httpsport)
});
var netserver = net.createServer(function(socket){
socket.once('data', function(buf){
console.log(buf[0]);
var address = buf[0] === 22 ? httpport : httpport;
var proxy = net.createConnection(address, function() {
proxy.write(buf);
socket.pipe(proxy).pipe(socket);
});
proxy.on('error', function(err) {
console.log(err);
});
});
socket.on('error', function(err) {
console.log(err);
});
}).listen(3344);
但是运行之后还报错3000端口被占用
Error: listen EADDRINUSE 0.0.0.0:3000
请问这个问题有什么办法解决?
皈依舞
相关分类