sudo apt update
sudo apt install mosquitto mosquitto-clients
sudo systemctl start mosquitto
sudo systemctl enable mosquitto
cd /etc/mosquitto/certs
把网站证书放到这里
nano /etc/mosquitto/mosquitto.conf
添加以下内容
# 允许匿名访问，可根据需要修改
allow_anonymous true

# 监听 WebSocket 端口
listener 8083
protocol websockets

# 监听 WebSocket TLS 端口
listener 8084
protocol websockets
cafile /etc/mosquitto/certs/server.crt
certfile /etc/mosquitto/certs/server.crt
keyfile /etc/mosquitto/certs/server.key

sudo systemctl restart mosquitto
验证配置
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MQTT WebSocket TLS Test</title>
    <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
</head>

<body>
    <script>
        const options = {
            protocol: 'wss',
            host: 'localhost',
            port: 8084,
            rejectUnauthorized: false // 因为是自签名证书，这里暂时设置为 false
        };

        const client = mqtt.connect(options);

        client.on('connect', function () {
            console.log('Connected to MQTT broker via WebSocket TLS');
            client.subscribe('test/topic', function (err) {
                if (!err) {
                    client.publish('test/topic', 'Hello, MQTT!');
                }
            });
        });

        client.on('message', function (topic, message) {
            console.log('Received message:', topic, message.toString());
            client.end();
        });
    </script>
</body>

</html>