websocket 如何在Socket.ioNodeJs中SSl www.example.com?

xghobddn  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(96)

在阅读了几乎所有的问题及其建议的解决方案后,我仍然没有得到一个安全的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 has version 4.6.2 and NodeJs has version 18.13.0

b0zn9rqh

b0zn9rqh1#

我让它工作了。在服务器代码中,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

从那里我得到了错误消息,证书无效。

相关问题