1.安装
npm install websocket
或
yarn add websocket
2.创建 WebSocket 连接:在你的 Vue 组件中,可以使用 WebSocket
对象来创建 WebSocket 连接。在 created
或 mounted
生命周期钩子中创建连接,并处理相应的事件。
import WebSocket from 'websocket';
import { getToken } from '@/utils/auth'
export default {
data() {
return {
socket: null,
};
},
created() {
this.socket = new WebSocket('ws://example.com',[getToken()]); // 替换为你的 WebSocket 服务器地址和token
this.socket.onopen = () => {
console.log('WebSocket 连接已建立');
// 在连接建立后,可以发送消息或执行其他操作
};
this.socket.onmessage = (event) => {
console.log('收到消息:', event.data);
// 处理收到的消息数据
};
this.socket.onclose = () => {
console.log('WebSocket 连接已关闭');
// 在连接关闭后,可以执行清理操作或重新连接等处理
};
},
beforeUnmount() {
if (this.socket) {
this.socket.close(); // 在组件销毁前关闭 WebSocket 连接
}
},
// ...
};
3.发送和接收消息:通过 socket.send()
方法发送消息到服务器,并通过监听 socket.onmessage
事件来接收服务器发送的消息。
4.关闭 WebSocket 连接:在适当的时机,可以调用 socket.close()
方法来关闭 WebSocket 连接。一般在onUnmounted生命周期中进行关闭
5.注意:上述示例中的 ws://example.com
是一个示例 WebSocket 服务器地址,你需要将其替换为你实际使用的 WebSocket 服务器地址。