点我去Gitee
点我去Gitee

mqtt与websocket最简单举例

一、websocket


    // const ws = new WebSocket(`ws://${SourceIP}:11523/ws/robot`);
    const ws = new WebSocket(`ws://xxx.xxx:xxxx/ws`);

    ws.addEventListener('message', ({ data }) => {

      console.log(data);

    });

    ws.onclose = function (e) {
      console.log('websocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
      console.log(e);

    };

  }

二、mqtt

import * as mqtt from "mqtt"

    const options = {
      clean: true,
      connectTimeout: 4000,
      clientId: "djfoadfnojdoijo",
    };
    const client = mqtt.connect("ws://broker.emqx.io:8083/mqtt", options);
    client.on("connect", () => {
      console.log("1链接成功");
      client.subscribe("test", (err) => {
        console.log('2订阅成功');
        if (!err) {
          console.log('3发布消息');
          client.publish("test", "Hello mqtt");
        }
      });
    });
    client.on("message", (topic, message) => {
      console.log('4订阅消息');
      console.log(topic);
      console.log(message.toString());
      client.end();
    });
  }



posted @ 2022-05-14 15:40  biuo  阅读(260)  评论(0编辑  收藏  举报