Socket.io - 通过https
我有我的虚拟服务器(Ubuntu的),它运行作为一个systemd服务,这是积极地运行,创造了一个socket.io聊天应用从客户机到服务器的连接。Socket.io - 通过https
我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连接,你将需要启用secure
在socketio(use this question as a ref)
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创建socketio服务器 您可以找到socket.io docs
注意此代码REF:您需要将您https不是http类似的例子所示
谢谢,但我不认为那是问题,因为你可以在中间从https://socket.io/docs/看到... VAR插座= 10(“socket.io”)(PORT)...已经创建了一个http服务器。 – Kelturio
如果你不提供一个,那么它会创建一个,如果你创建了自己的并使用它创建套接字服务器,它将使用你创建的套接字服务器。 – y0hami
@Kelturio它创建_HTTP_服务器,而不是_HTTPS_服务器。 – robertklep
好,socket.io是在其上没有Web服务器,那么你将使用节点http或expressjs在server.js需要安装一个服务器。见https://socket.io/docs/ –
但大约2年前,我得到了同样的server.js工作。我不知道自那以后发生了什么变化。 server.js使用/ usr/bin/node永久运行。 – Kelturio