首页 > 解决方案 > 通过 https 的 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 服务器?

标签: httpswebsocketsocket.io

解决方案


根据文档

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');

推荐阅读