1.创建一个 WebSocketService.js 文件来封装 WebSocket 的功能。
这个文件将处理 WebSocket 的连接、消息发送和接收。
// utils/WebSocketService.js
// import server from '../config/server';
class WebSocketService {
constructor(url) {
// 构造函数,初始化 WebSocket 的 URL、socket 对象、监听器、连接状态
// let serverUrl=String(server.substring(server.indexOf("/")))
// this.url = 'ws:'+serverUrl+url; // 截取后拼接的url链接,用下面的就可以
this.url = url; // WebSocket 服务器的 URL
this.socket = null; // WebSocket 实例
this.listeners = []; // 存储事件监听器
this.isConnected = false; // WebSocket 是否已连接的状态
}
// 创建 WebSocket 连接
connect() {
// 如果已连接,则不再重新连接
// if (this.socket) {
// console.log("WebSocket already connected.");
// return;
// }
// 创建 WebSocket 实例并设置连接 URL
this.socket = new WebSocket(this.url);
// 连接成功后的回调函数
this.socket.onopen = () => {
this.isConnected = true; // 设置连接状态为已连接
console.log("WebSocket connected");
this._notifyListeners("open"); // 通知所有监听器连接已建立
};
// 连接关闭后的回调函数
this.socket.onclose = () => {
this.isConnected = false; // 设置连接状态为已关闭
console.log("WebSocket disconnected");
this._notifyListeners("close"); // 通知所有监听器连接已关闭
};
// 连接错误的回调函数
this.socket.onerror = (error) => {
console.error("WebSocket error", error);
this._notifyListeners("error", error); // 通知所有监听器发生错误
};
// 接收到消息时的回调函数
this.socket.onmessage = (message) => {
this._notifyListeners("message", message); // 通知所有监听器有新消息
};
}
// 发送消息到服务器
send(message) {
// 只有在连接已打开时才能发送消息
if (this.isConnected && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(message); // 发送消息
console.log("Sent message:", message);
} else {
console.error("WebSocket is not open. Cannot send message."); // 如果未连接,输出错误
}
}
// 监听事件
on(event, callback) {
// 将事件和回调函数存入监听器数组
this.listeners.push({ event, callback });
}
// 通知所有监听器事件发生
_notifyListeners(event, data) {
// 遍历所有监听器,如果事件匹配,则调用回调函数
this.listeners.forEach((listener) => {
if (listener.event === event) {
listener.callback(data);
}
});
}
// 关闭连接
close() {
// 如果 WebSocket 实例存在,关闭连接
if (this.socket) {
this.socket.close(); // 关闭 WebSocket
console.log("WebSocket connection closed");
}
}
}
// // 单例模式:确保整个应用中只创建一个 WebSocketService 实例
// let wsInstance = null;
// // 获取 WebSocketService 单例实例
// export function getWebSocketInstance(url) {
// // 如果实例不存在,则创建新实例
// if (!wsInstance) {
// wsInstance = new WebSocketService(url);
// }
// return wsInstance;
// }
// 直接返回一个新的 WebSocketService 实例,不使用单例模式,确保每次调用时都能创建一个新的实例
export function getWebSocketInstance(url) {
return new WebSocketService(url);
}
2. 在 Vue 组件中引用 WebSocket
你可以在需要使用 WebSocket 的 Vue 组件中引入并使用上面封装WebSocketService。
<template>
<div>
<h2>WebSocket Demo</h2>
<div>
<button @click="sendMessage">发送消息</button>
<p>{{ message }}</p>
</div>
</div>
</template>
<script>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { getWebSocketInstance } from "../../../utils/WebSocketService.js";
export default {
name: "WebSocketComponent",
setup() {
const message = ref("");
// 因为不想自己搭建 WebSocket 服务器,所以直接使用在线的 WebSocket 测试平台,可以把这个链接放到下面"wss://echo.websocket.org/"去测试。
const wsUrl = "wss://echo.websocket.org/"; // 替换为你实际的 WebSocket URL
const socketService = getWebSocketInstance(wsUrl);
// let intervalId; // 用于存储定时器的ID
// 连接 WebSocket
onMounted(() => {
socketService.connect();
// 监听 WebSocket 消息
socketService.on("message", (msg) => {
message.value = msg.data;
console.log("Received message:", msg.data);
});
socketService.on("open", () => {
console.log("WebSocket opened");
// intervalId = setInterval(sendMessage, 5000); // 每5秒发送一条数据
});
socketService.on("close", () => {
// clearInterval(intervalId); // 清除定时器
console.log("WebSocket closed");
});
socketService.on("error", (error) => {
console.error("WebSocket error", error);
});
});
// 发送消息
const sendMessage = () => {
const msg = "你好!";
socketService.send(msg);
console.log("Sent message:", msg);
// const message = {
// vibrationMax: Math.random() * 100,
// vibrationEffective: Math.random() * 100,
// displacement: Math.random() * 100,
// };
// socketService.send(JSON.stringify(message));
// console.log("Sent message:", message);
};
// 清理工作
onBeforeUnmount(() => {
socketService.close();
});
return {
message,
sendMessage
};
}
};
</script>
<style scoped>
h2 {
color: #4CAF50;
}
button {
padding: 10px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #45a049;
}
</style>
WebSocket 测试平台
WebSocket Echo Test,是一个提供 WebSocket 测试功能的平台。