提问人:ArchibaldTuttle 提问时间:6/21/2023 更新时间:6/22/2023 访问量:36
如何在NodeJs中SSl Socket.io?
How to SSl Socket.io in NodeJs?
问:
在阅读了几乎所有问题及其建议的解决方案后,我仍然无法获得安全的 websocket 连接。
没有SSL,它就像一个魅力。
这是我的非安全服务器:
const http = require('http');
const { Server } = require('socket.io');
const port = 8025;
const httpServer = http.createServer((req, res) => {
res.writeHead(200);
res.end("Server is responding!");
})
const io = new Server(httpServer);
io.on('connection', (socket) => {
socket.onAny((event, args) => {
console.log('event:', event, 'args:', args);
io.emit(event, args);
});
});
httpServer.listen(port, () => {
console.log(`Socket.io server running at http://localhost:${port}/`);
});
这是我的不安全客户端:
const io = require('socket.io-client');
const socket = io('ws://example.com:8025');
socket.on('message', (args) => {
console.log('client args', args);
});
socket.emit('message', 'one message ' + Date.now());
但这失败了,例如,连接不起作用:
服务器:
const fs = require('fs');
const https = require('https');
const { Server } = require('socket.io');
const port = 8025;
const options = {
key: fs.readFileSync('/etc/apache2/ssl/spl.audio.key.pem'),
cert: fs.readFileSync('/etc/apache2/ssl/spl.audio.crt.pem'),
};
const httpsServer = https.createServer(options, (req, res) => {
res.writeHead(200);
res.end("Server is responding!");
})
const io = new Server(httpsServer);
io.on('connection', (socket) => {
socket.onAny((event, args) => {
console.log('event:', event, 'args:', args);
io.emit(event, args);
});
});
httpsServer.listen(port, () => {
console.log(`Socket.io server running at https://localhost:${port}/`);
});
客户:
const io = require('socket.io-client');
const socket = io('wss://example.com:8025');
socket.on('message', (args) => {
console.log('client args', args);
});
socket.emit('message', 'one message ' + Date.now());
Socket.io 的版本为 4.6.2,NodeJs 的版本为 18.13.0
答:
0赞
ArchibaldTuttle
6/22/2023
#1
我让它工作了。在服务器代码中,ca 证书是强制性的:
const options = {
key: fs.readFileSync('/etc/apache2/ssl/spl.audio.key.pem'),
cert: fs.readFileSync('/etc/apache2/ssl/spl.audio.crt.pem'),
ca: fs.readFileSync('/etc/apache2/ssl/spl.audio.ca.pem')
};
我的好主意是让客户从
DEBUG=* node index.js
从那里我收到错误消息,证书无效。
评论