1

我的机器上运行着 mosquitto MQTT 代理。我想从浏览器运行 MQTT 客户端。这是我在 Django 应用程序中所做的:

<html>
  <head>
    <title>Mosquitto Websockets</title>
    {% load staticfiles %}
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="{% static 'js/mqttws31-min.js' %}" type="text/javascript"></script>
    <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script>
    <script src="{% static 'js/config.js' %}" type="text/javasacript"></script>
    <script type="text/javascript">
    var mqtt;
    var reconnectTimeout = 2000;

    function MQTTconnect() {
        host = '127.0.0.1';
        port = 1883;
        useTLS = false;
        cleansession = true;
        username = null;
        password = null;
        mqtt = new Paho.MQTT.Client(host, port,
                    "myclientid_" + parseInt(Math.random() * 100, 10));

        /*mqtt = new Messaging.Client(
                        host,
                        port,
                        "web_" + parseInt(Math.random() * 100,
                        10));
        */
        var options = {
            timeout: 3,
            useSSL: useTLS,
            cleanSession: cleansession,
            onSuccess: onConnect,
            onFailure: function (message) {
                $('#status').val("Connection failed: " + message.errorMessage + "Retrying");
                setTimeout(MQTTconnect, reconnectTimeout);
            }
        };

        mqtt.onConnectionLost = onConnectionLost;
        mqtt.onMessageArrived = onMessageArrived;

        if (username != null) {
            options.userName = username;
            options.password = password;
        }
        console.log("Host="+ host + ", port=" + port + " TLS = " + useTLS + " username=" + username + " password=" + password);
        mqtt.connect(options);
    }

    function onConnect() {
        $('#status').val('Connected to ' + host + ':' + port);
        // Connection succeeded; subscribe to our topic
        mqtt.subscribe(topic, {qos: 0});
        $('#topic').val(topic);
    }

    function onConnectionLost(response) {
        setTimeout(MQTTconnect, reconnectTimeout);
        $('#status').val("connection lost: " + responseObject.errorMessage + ". Reconnecting");

    };

    function onMessageArrived(message) {

        var topic = message.destinationName;
        var payload = message.payloadString;

        $('#ws').prepend('<li>' + topic + ' = ' + payload + '</li>');
    };


    $(document).ready(function() {
        MQTTconnect();
    });

    </script>
  </head>
  <body>
    <h1>Mosquitto Websockets</h1>
    <div>
        <div>Subscribed to <input type='text' id='topic' disabled />
        Status: <input type='text' id='status' size="80" disabled /></div>

        <ul id='ws' style="font-family: 'Courier New', Courier, monospace;"></ul>
    </div>
  </body>
</html>

我明白了

WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET   mqttws31-min.js:15
Host=127.0.0.1, port=1883 TLS = false username=null password=null   (index):47

我是新手,所以无法解决这个问题。有什么帮助吗?

Edit1:我调整了配置文件,现在它成功连接到 test.mosquitto.org:8080。我订阅了#,但它无法检索已发布的消息。我认为功能onMessageArrived(message)不起作用。控制台中没有错误,因此无法识别任何错误。

在此处输入图像描述

4

3 回答 3

3

您确定您已将代理配置为接受端口 1883 上的 websockets 连接吗?默认情况下,您希望它监听 MQTT 连接,而不是 websocket。

尝试将以下内容放入您的配置文件中:

listener 8080
protocol websockets

正如 Scott 所说,您可以尝试将您的客户端连接到 test.mosquitto.org:8080 以查看它是否有效。

于 2015-03-03T07:30:26.817 回答
1

这是一个运行“MQTT over Websockets”服务器的站点,其中 URL 可以充当客户端,以便您可以发布,然后让您自己的浏览器充当订阅给定主题的客户端

http://test.mosquitto.org/ws.html

它可能会让你梳理连接问题......这里还有另一个实现类似功能的nodejs库

https://www.npmjs.com/package/mqtt-ws
于 2015-03-03T04:08:53.917 回答
0

Based on your comment @toothie

"I tried connecting to 'test.mosquitto.org' and got this error: WebSocket connection to 'ws://test.mosquitto.org/:1883/mqtt' failed: Error during WebSocket handshake: Unexpected response code: 404"

The connection string you are sending seems bad formatted. How are you building it?

For me, the separation of concerns using the JSON object definition to instance the library saved me from a couple of headaches:

{
    protocol: 'wss',
    host: `${process.env.MQTT_ENDPOINT}`,
    port: 9001,
    username: 'admin',
    password: '123'
}

Maybe something is helpful for you.

于 2020-03-27T20:58:25.027 回答