https - 通过 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 服务器?
解决方案
根据文档:
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');
推荐阅读
- python - 优化生成和拆分列表的内存使用
- node.js - res.redirect(url) 只能间歇性工作
- app-store - App Store 内部分发无法添加我的组织 ID
- shell - AWK 在平局期间为排名分配分配上限值
- node.js - 为什么我的 Flutter 应用无法连接到我的本地 nodejs 服务器?
- java - 将两个具有共享数据库的 Spring Boot 应用程序部署到 AWS(架构)中
- c# - C# MetaData API ValueSetValuesDefinition CS0029不能隐式转换类型'System.Collections.Generic.List
- sql - 插入 table_name values () (select ...)
- regex - 正则表达式:查找彼此相距 10 个单词以内的单词
- ruby-on-rails - 无法加载此类文件 -- rails/commands (LoadError)