通过https的Socket.io服务器

时间:2020-05-03 00:12:21

标签: https websocket socket.io

我试图将套接字IO入门示例转换为https:

const fs = require('fs');
const app = require('https').createServer({
    key: fs.readFileSync("privkey.pem"),
    cert: fs.readFileSync("cert.pem"),
    ca: fs.readFileSync("fullchain.pem"),
}, handler)
const io = require('socket.io')(app);

app.listen(443);

function handler (req, res) {
    res.writeHead(200);
    res.end();
}

io.on('connection', (socket) => {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', (data) => {
    console.log(data);
  });
});

但是在我的浏览器中运行以下命令无效:

const ws = new WebSocket("wss://example.com");

但是我收到以下错误:

Firefox can’t establish a connection to the server at wss://example.com/.

我试图通过运行以下curl命令来调试它:

curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: example.com" -H "Origin: https://example.com " https://example.com

结果是:

curl: (52) Empty reply from server

所有控制台日志代码均未到达,并且在执行所有这些操作时,节点脚本上没有错误。

为什么我不能连接到我的websocket服务器?

1 个答案:

答案 0 :(得分:0)

根据doc

Socket.IO不是WebSocket实现。尽管Socket.IO确实确实在可能的情况下使用WebSocket作为传输工具,但是它在每个数据包中添加了一些元数据:当需要消息确认时,数据包类型,名称空间和数据包ID。因此,WebSocket客户端将无法成功连接到Socket.IO服务器,而Socket.IO客户端也将无法连接到WebSocket服务器。

所以这是不正确的:

const ws = new WebSocket("wss://example.com");

您应该使用:

const socket = io('https://your-server-address');