我在我的虚拟服务器 (Ubuntu) 上创建了一个 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.
可能是什么错误?
最佳答案
根据我过去所做的,我将创建一个 https 服务器来提供 SSL 证书,并使用您创建的 https 服务器创建套接字服务器,这将允许您通过 https 连接,并且您需要在 socketio ( use this question as a ref ) 上启用 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 创建套接字服务器的引用 您可以在 socket.io docs 上找到此代码
注意:您将需要 https 而不是示例中所示的 http
关于javascript - Socket.io - 通过 https 从客户端连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589321/