nodejs + socket.io 同时使用http 和 https
发布于 9 年前 作者 jShi-git 16470 次浏览 最后一次编辑是 8 年前 来自 问答

socket.io和nodejs如果需要同时支持http和https的话需要怎么设置

nginx https 什么的已经设置好了

//端口
var port = normalizePort(process.env.PORT || 3002);
var https_port = normalizePort(process.env.HTTPS_PORT || 443);

//https证书
var opts = {
  key: fs.readFileSync('pem/openssl/ssl.key'),
  cert: fs.readFileSync('pem/openssl/ssl.crt')
};

var server = http.createServer(handler);
var httpsServer = https.createServer(opts, function(req, res) {
  res.writeHead(200, {
    "Content-Type": "text/plain"
  });
  res.write("hello https");
  res.end();
});

server.listen(port);
httpsServer.listen(https_port);

server.on('error', onError);
server.on('listening', onListening);

httpsServer.on('error', onError);
httpsServer.on('listening', onListening);

//socket.io
var io = require('socket.io')({});			<-------- 这里改如何设置

io.attach(server);
io.attach(httpsServer);
6 回复

已经使用比较笨的办法解决…

...
//socket.io
var io = require('socket.io')(http, {});			
var iossl = require('socket.io')(https, {});
...

不用nginx?

为啥这么纠结的呢?全部https不可以吗?

应该是 wss:// 才对

// socketio:2.3.0 node:14.16.1 // 生成证书: // openssl genrsa -des3 -out server.pass.key 2048 // openssl rsa -in server.pass.key -out server.key // openssl req -new -key server.key -out server.csr -subj “/C=CN/ST=HangZhou/L=XIAOSHAN/O=localhost/OU=localhost/CN=localshot” // openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt #生成证书 const port = 3000 const sport = 3001 const option = { “key”: fs.readFileSync(’./ts_output/pem/server.key’, ‘utf8’), “cert”: fs.readFileSync(’./ts_output/pem/server.crt’, ‘utf8’) };

var httpServer = require(‘http’).createServer(); var httpsServer = require(‘https’).createServer(option); var sio = require(‘socket.io’)(httpServer); var ssio = require(‘socket.io’)(httpsServer);

sio.on(‘connection’, function(client){ console.log(’-----------no ssl-----------------’) }); });

ssio.on(‘connection’, function(client){ console.log(’-----------ssl-----------------’) }); });

httpServer.listen(port); httpsServer.listen(sport) console.log(‘sio Server listening at port %d’, port); console.log(‘ssio Server listening at port %d’, sport); // Uncaught exception handler process.on(‘uncaughtException’, function(err) { console.error(’ Caught exception: ’ + err.stack); });

回到顶部