当前位置:   article > 正文

websocket连接、mqtt连接_mqtt websocket连接

mqtt websocket连接

websocket连接

mounted() {
	this.initWebSocket();
},
  • 1
  • 2
  • 3

websocket相关函数封装

initWebSocket() { 
	this.ws = new WebSocket('ws://...');
	this.ws.onopen = () => {
	  console.log('push_ws:onopen');
	};
	this.ws.onclose = () => {
	  this.ws.onmessage = null;
	  this.ws = null;
	  console.log('push_ws:onclose');
	};
	this.ws.onerror = () => {
	  this.ws = null;
	  console.log('push_ws:onerror');
	};
	this.ws.onmessage = (e) => {
		console.log(e)
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

mqtt连接,组件化引入

<template>
  <div></div>
</template>

<script>
  import mqtt from 'mqtt';
  import { defineComponent, reactive, onBeforeUnmount, onMounted, watch, unref } from 'vue';

  export default defineComponent({
    name: 'MqttConnect',
    props: {
      host: {
        default: '',
        type: String,
      },
      port: {
        default: 28083,
        type: Number,
      },
      subscription: {
        default: [],
        type: Array[String],
      },
    },
    setup(prop, { emit }) {
      onBeforeUnmount(() => {
        destroyConnection();
      });
      onMounted(() => {
        createConnection();
      });
      const data = reactive({
        connection: {
          host: '',
          port: null,
          endpoint: '/mqtt',
          clean: true, // 保留会话
          connectTimeout: 4000, // 超时时间
          //reconnectPeriod: 4000, // 重连时间间隔
          // 认证信息
          clientId: 'mqttjs_3be2c321',
          username: '',
          password: '',
        },
        publish: {
          topic: 'home/garden/fountain',
          qos: 0,
          payload: '{ "msg": "Hello, I am browser." }',
        },
        receiveNews: '',
        qosList: [
          { label: 0, value: 0 },
          { label: 1, value: 1 },
          { label: 2, value: 2 },
        ],
        client: {
          connected: false,
        },
        subscribeSuccess: false,
      });
      // 创建连接
      const createConnection = () => {
        data.connection.host = prop.host;
        data.connection.port = prop.port;
        data.connection.clientId = 'mqttjs_3be2c321' + Math.random() * 100000;
        const { host, port, endpoint, ...options } = data.connection;
        let connectUrl;
        if (window.location.href.indexOf('https') !== -1)
          connectUrl = 'wss://www.hikailink-cloud.com/mqtt8083';
        else connectUrl = `ws://${host}:${port}${endpoint}`;
        data.client = mqtt.connect(connectUrl, options);
        data.client.on('connect', () => {
          console.log('Connection succeeded!');
        });
        data.client.on('error', (error) => {
          console.log('Connection failed', error);
        });
        data.client.on('message', (topic, message) => {
          if (message.toString()) {
            emit('getMessage', topic, JSON.parse(message.toString()));
          }
        });
        prop.subscription.forEach((item) => {
          doSubscribe(item, 0);
        });
      };
      // 订阅主题
      const doSubscribe = (topic, qos) => {
        data.client.subscribe(topic, { qos }, (error, res) => {
          if (error) {
            console.log('Subscribe to topics error', error);
            return;
          }
          data.subscribeSuccess = true;
          console.log('Subscribe to topics res', res);
        });
      };
      // 取消订阅
      const doUnSubscribe = (topic) => {
        data.client.unsubscribe(topic, (error) => {
          if (error) {
            console.log('Unsubscribe error', error);
          }
        });
      };
      // 断开连接
      const destroyConnection = () => {
        if (data.client.connected) {
          try {
            data.client.end();
            data.client = {
              connected: false,
            };
            console.log('Successfully disconnected!');
          } catch (error) {
            console.log('Disconnect failed', error.toString());
          }
        }
      };
      watch(
        () => unref(prop).subscription,
        (subscription, old) => {
          old.forEach((item) => {
            doUnSubscribe(item);
          });
          setTimeout(() => {
            subscription.forEach((item) => {
              doSubscribe(item, 0);
            });
          }, 300);
        }
      );
    },
  });
</script>

<style scoped></style>

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/962321
推荐阅读
相关标签
  

闽ICP备14008679号