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

查看:203
本文介绍了Node.js,socket.io https连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务器端代码:

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

});

客户端代码:

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

});

在http上,它在未连接的同一页面上使用https. 搜索了许多示例,但所有示例均表达出来.我不需要在node.js中创建任何http服务器,只需要做socket.io工作即可.

On http it's worked on https in same page it not connected. Searched many examples, but all example for express. I dont create any http server in node.js need only to socket.io work.

推荐答案

通过HTTPS运行客户端时,socket.io也会尝试通过HTTPS连接到服务器.当前,您的服务器仅接受HTTP连接,listen(port)函数不支持HTTPS.

When running the client over HTTPS, socket.io is attempting to connect to your server over HTTPS as well. Currently your server is only accepting HTTP connections, the listen(port) function does not support HTTPS.

您需要创建一个HTTPS服务器,然后将socket.io附加到它,就像这样.

You'll need to create an HTTPS server and then attach socket.io to it, something like this.

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) {

});

如果同时需要HTTP和HTTPS,则可以启动两个服务器并将socket.io附加到这两个服务器上.

And if you need both HTTP and HTTPS, you can start two servers and attach socket.io to both.

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) {

});

然后在客户端,您可以根据是通过HTTP还是HTTPS访问该页面来确定要连接到哪个端口.

Then on the client side you can determine which port to connect to based on whether the page was accessed over HTTP or HTTPS.

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

});

这篇关于Node.js,socket.io https连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆