Socket.io – 通过https从客户端连接到服务器

我在我的虚拟服务器(Ubuntu)上创build了一个socket.io聊天应用程序,它作为systemd服务运行,并且正在运行。

我的server.js位于:

/var/www/vhosts/mywebpage.de/w1.mywebpage.de/chat/ 

server.js看起来像这样:

 const io = require('socket.io')(3055); io.on('connection', function(socket) { // When the client emits 'addUser', this listens and executes socket.on('addUser', function(username, room) { ... }); // When the client emits 'sendMessage', this listens and executes socket.on('sendMessage', function(msg) { ... }); // Disconnect the user socket.on('disconnectUser', function(username, room) { ... }); }); 

在我的网站(https),我尝试连接如下:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.3/socket.io.js"></script> <script type="text/javascript"> var loSocket; $(document).ready(function() { if(typeof(loSocket) == 'undefined') { loSocket = io('https://w1.mywebpage.de:3055', { reconnectionAttempts: 5, forceNew: true }); } }); </script> 

但是我无法获得有效的连接。

开发人员工具说:

 (failed) ERR_CONNECTION_CLOSED with initiator polling-xhr.js:264. 

什么可能是错误?

根据我以前的做法,我将创build一个https服务器,它提供SSL证书,并使用您创build的https服务器创build套接字服务器,这将允许您通过https进行连接,并且需要启用socketio上的secure性( 使用这个问题作为参考 )

 var app = require('http').createServer(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(80); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); 

使用这个代码作为参考如何使用http创build一个socketio服务器你可以find这个代码在socket.io文档

注意:您将需要https,而不是像示例中所示的http