自学内容网 自学内容网

SSE与WebSocket与MQTT

SSE

<template>
  <div>
    <h1>实时消息</h1>
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const messages = ref([]);  // 存储接收到的消息
let eventSource;

onMounted(() => {
  // 创建 SSE 连接
  eventSource = new EventSource('https://example.com/sse-endpoint');

  // 监听消息事件
  eventSource.onmessage = (event) => {
    messages.value.push(event.data);  // 将新消息推入列表
  };

  // 监听错误事件
  eventSource.onerror = (error) => {
    console.error('SSE 连接错误:', error);
    eventSource.close();  // 出现错误时可以选择关闭连接
  };
});

onUnmounted(() => {
  // 组件卸载时关闭 SSE 连接
  if (eventSource) {
    eventSource.close();
  }
});
</script>

WebSocket

<template>
  <div>
    <h1>实时聊天</h1>
    <input v-model="newMessage" @keydown.enter="sendMessage" placeholder="输入消息" />
    <ul>
      <li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const messages = ref([]);    // 存储接收到的消息
const newMessage = ref('');   // 存储输入框的消息内容
let socket;

onMounted(() => {
  // 创建 WebSocket 连接
  socket = new WebSocket('wss://example.com/socket-endpoint');

  // 监听消息事件
  socket.onmessage = (event) => {
    messages.value.push(event.data);  // 将接收到的消息添加到列表中
  };

  // 监听错误事件
  socket.onerror = (error) => {
    console.error('WebSocket 错误:', error);
  };

  // 监听 WebSocket 连接关闭
  socket.onclose = () => {
    console.log('WebSocket 连接已关闭');
  };
});

onUnmounted(() => {
  // 组件卸载时关闭 WebSocket 连接
  if (socket) {
    socket.close();
  }
});

// 发送消息
const sendMessage = () => {
  if (newMessage.value) {
    socket.send(newMessage.value);  // 发送消息到服务器
    newMessage.value = '';  // 清空输入框
  }
};
</script>

MQTT

// src/mqttService.js
import mqtt from 'mqtt';

let client;

export const connectMQTT = () => {
  client = mqtt.connect('wss://broker.hivemq.com:8000/mqtt');  // 替换为你的 MQTT 代理地址
  
  client.on('connect', () => {
    console.log('MQTT connected');
    client.subscribe('test/topic', (err) => {
      if (!err) {
        console.log('Subscribed to test/topic');
      }
    });
  });

  client.on('message', (topic, message) => {
    console.log(`Received message: ${message.toString()} from topic: ${topic}`);
  });
};

export const publishMessage = (topic, message) => {
  if (client && client.connected) {
    client.publish(topic, message);
    console.log(`Message sent: ${message} to topic: ${topic}`);
  }
};

export const disconnectMQTT = () => {
  if (client) {
    client.end();
    console.log('MQTT disconnected');
  }
};
<template>
  <div>
    <h1>Vue 3 with MQTT</h1>
    <button @click="sendMessage">Send Message</button>
    <p>Message: {{ receivedMessage }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { connectMQTT, publishMessage, disconnectMQTT } from './mqttService';

const receivedMessage = ref('');

const sendMessage = () => {
  publishMessage('test/topic', 'Hello from Vue 3!');
};

onMounted(() => {
  connectMQTT();
});

onBeforeUnmount(() => {
  disconnectMQTT();
});

// 订阅消息并更新界面
import { watchEffect } from 'vue';
watchEffect(() => {
  // 这里可以根据接收到的消息更新UI
  // 对接收到的消息进行处理
  receivedMessage.value = 'Waiting for messages...';
});
</script>

<style scoped>
button {
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
}
</style>


原文地址:https://blog.csdn.net/Davoid/article/details/143714076

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!