简体   繁体   English

Node.js、socket.io https 连接

[英]Node.js, socket.io https connection

Server side code:服务器端代码:

var io = require('socket.io').listen(8150);
io.sockets.on('connection', function (socket){

});

Client side code:客户端代码:

var socketIO = io('*.*.*.*:8150');
socketIO.once('connect', function(){

});

On http it's worked on https in same page it not connected.在 http 上,它在同一页面上的 https 上工作,但未连接。 Searched many examples, but all example for express.搜索了很多例子,但所有例子都是快递。 I dont create any http server in node.js need only to socket.io work.我没有在 node.js 中创建任何 http 服务器只需要 socket.io 工作。

When running the client over HTTPS, socket.io is attempting to connect to your server over HTTPS as well.通过 HTTPS 运行客户端时,socket.io 也会尝试通过 HTTPS 连接到您的服务器。 Currently your server is only accepting HTTP connections, the listen(port) function does not support HTTPS.目前您的服务器只接受 HTTP 连接, listen(port)功能不支持 HTTPS。

You'll need to create an HTTPS server and then attach socket.io to it, something like this.您需要创建一个 HTTPS 服务器,然后将 socket.io 附加到它,就像这样。

var fs = require('fs');

var options = {
  key: fs.readFileSync('certs/privkey.pem'),
  cert: fs.readFileSync('certs/fullchain.pem')
};

var app = require('https').createServer(options);
var io = require('socket.io').listen(app);
app.listen(8150);

io.sockets.on('connection', function (socket) {

});

And if you need both HTTP and HTTPS, you can start two servers and attach socket.io to both.如果您同时需要 HTTP 和 HTTPS,您可以启动两个服务器并将 socket.io 附加到两者。

var fs = require('fs');

var options = {
  key: fs.readFileSync('certs/privkey.pem'),
  cert: fs.readFileSync('certs/fullchain.pem')
};

var httpServer = require('http').createServer();
var httpsServer = require('https').createServer(options);
var ioServer = require('socket.io');

var io = new ioServer();
io.attach(httpServer);
io.attach(httpsServer);
httpServer.listen(8150);
httpsServer.listen(8151);

io.sockets.on('connection', function (socket) {

});

Then on the client side you can determine which port to connect to based on whether the page was accessed over HTTP or HTTPS.然后在客户端,您可以根据页面是通过 HTTP 还是 HTTPS 访问来确定要连接到哪个端口。

var port = location.protocol === 'https:' ? 8151 : 8150;
var socketIO = io('*.*.*.*:' + port);
socketIO.once('connect', function() {

});

Use letsencrypt with Plesk for a valid SSL certificat.将letsencrypt 与Plesk 一起使用以获得有效的SSL 证书。

options = {
    key: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/privkey.pem'),
    cert: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/cert.pem'),
    ca: fs.readFileSync('/usr/local/psa/var/modules/letsencrypt/etc/live/mydomain.com/chain.pem'),
    rejectUnauthorized: false,
    requestCert: true,
    agent: false
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM