回车发送数据,模拟服务器发送数据
效果图:
源码:
<template><div><h1>WebSocket 实时数据</h1><input type="text" v-model="ipt" @keyup.enter="sendMessage(ipt)"><div v-if="message"><h3>接收到的数据:</h3><pre>{{ message }}</pre></div><div v-else><p>等待 WebSocket 消息...</p></div></div></template><script>export default {data() {return {ipt:'',ws: null, // WebSocket 实例message: null, // 接收到的消息isConnected: false, // 是否已连接};},methods: {// 初始化 WebSocket 连接initWebSocket() {const wsUrl = 'ws://124.222.224.186:8800'; // WebSocket 服务器 URLthis.ws = new WebSocket(wsUrl);// 连接打开时的回调this.ws.onopen = () => {console.log('WebSocket 已连接');this.isConnected = true;};// 接收到消息时的回调this.ws.onmessage = (event) => {console.log('收到消息:', event.data);this.message = event.data.slice(19); // 更新接收到的消息};// 连接关闭时的回调this.ws.onclose = () => {console.log('WebSocket 连接关闭');this.isConnected = false;};// 连接错误时的回调this.ws.onerror = (error) => {console.error('WebSocket 错误:', error);};},// 发送消息到 WebSocket 服务器sendMessage(message) {if (this.ws && this.ws.readyState === WebSocket.OPEN) {this.ws.send(message);console.log('发送消息:', message);} else {console.log('WebSocket 连接未开启');}},},// Vue 生命周期钩子mounted() {// 组件挂载时初始化 WebSocket 连接this.initWebSocket();},beforeDestroy() {// 在组件销毁之前,关闭 WebSocket 连接if (this.ws) {this.ws.close();console.log('WebSocket 连接已关闭');}},};</script><style scoped>h1 {color: #333;}pre {background-color: #f4f4f4;padding: 10px;border-radius: 5px;}</style>