当前位置 博文首页 > 程序员石磊:Paho JavaScript Client 基于websocket实现 mqtt客

    程序员石磊:Paho JavaScript Client 基于websocket实现 mqtt客

    作者:[db:作者] 时间:2021-08-08 19:19

    mqtt服务器采用activemq实现。

    1. 首先配置activemq支持websocket.
      具体配置,请点击activemq官网配置。
    2. 编写客户端页面,引入Paho官方客户端js库。
      具体配置,请点击查看
      贴出关键代码如下:
    // Create a client instance
    //注意不要在client前写var
    client = new Paho.MQTT.Client(location.hostname, Number(location.port), "clientId");
    
    // set callback handlers
    client.onConnectionLost = onConnectionLost;
    client.onMessageArrived = onMessageArrived;
    
    // connect the client
    client.connect({onSuccess:onConnect});
    
    
    // called when the client connects
    function onConnect() {
      // Once a connection has been made, make a subscription and send a message.
      console.log("onConnect");
      client.subscribe("World");
      message = new Paho.MQTT.Message("Hello");
      message.destinationName = "World";
      client.send(message);
    }
    
    // called when the client loses its connection
    function onConnectionLost(responseObject) {
      if (responseObject.errorCode !== 0) {
        console.log("onConnectionLost:"+responseObject.errorMessage);
      }
    }
    
    // called when a message arrives
    function onMessageArrived(message) {
      console.log("onMessageArrived:"+message.payloadString);
    }

    注意不要在client前写var
    否则你可能会出现一下错误:

    https://www.eclipse.org/forums/index.php/t/1068818/

    cs