Mosquitto设置websockets(wss)服务器及使用javascript客户端连接

最近项目需要使用 MQTT服务,出于安全考虑,web服务器使用了 https,web连接mqtt服务器也使用了websockets(wss)

Mosquitto配置websockets

mosquitto.conf 添加:

listener 8081
protocol websockets
cafile /home/phpquan.com/1_root_bundle.crt        #根证书
certfile /home/phpquan.com/2_phpquan.com.crt      #域名证书crt
keyfile /home/phpquan.com/3_phpquan.com.key       #域名证书key

重启后就启用成功

javascript客户端连接

javascript客户端使用:Eclipse Paho JavaScript Client

官方链接:https://www.eclipse.org/paho/index.php?page=clients/js/index.php

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MQTT</title>
    <script src="/js/mqttws31.js"></script>
</head>
<body>

<script>
    //mqtt
    var mqtt;
    function MQTTconnect() {
        mqtt = new Paho.MQTT.Client('phpquan.com', 8081, (Math.random() * 1000000000).toString());
        var options = {
            timeout: 0,
            onSuccess: onConnect,
            onFailure: onFailure,
            userName: 'userName',
            password: 'password',
            useSSL: true,  //启用ssl
            mqttVersion: 4
        };
        mqtt.onMessageArrived = onMessageArrived;
        mqtt.connect(options);
    }
    function onConnect() {
        console.log('connected.');
        let i=0;
        let timer = setInterval(() => {
            i++;

            //发送消息
            var raw_message = '信息!'+i;
            message = new Paho.MQTT.Message(raw_message);
            message.destinationName = 'stu';  //topic
            console.log('sending message: ' + raw_message);
            mqtt.send(message);
            if(i >= 3){
                clearInterval(timer);
            }
        },1000)
        // 订阅 topic
        var subOptions = {
            qos: 0,
            onSuccess: onSubscribe
        };
        mqtt.subscribe('$SYS/broker/#', subOptions); //关注系统消息
    }

    // 订阅主题成功事件
    function onSubscribe(context) {
        console.log('subscribe success');
        console.log(context);
    }

    // 连接失败事件
    function onFailure(message) {
        console.log('connect failed.');
    }

    function onMessageArrived(message) {
        console.log(message.destinationName,message.payloadString);
    }

    MQTTconnect();

</script>
</body>
</html>
html根据自己的mqtt配置修改连上就成功