一、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();
});
}