uniapp websocket
时间: 2025-02-19 20:22:58 浏览: 31
### 如何在 UniApp 中实现 WebSocket 实时通信
#### 创建 WebSocket 封装类
为了简化 WebSocket 的使用,在项目中创建一个新的 JavaScript 文件 `WebSocketService.js` 来定义一个服务类,该类负责管理与服务器之间的 WebSocket 连接。此文件实现了基本的连接逻辑以及重连机制。
```javascript
// src/utils/WebSocketService.js
export default class WebSocketService {
constructor(url, protocols = []) {
this.url = url;
this.protocols = protocols;
this.ws = null;
this.reconnectInterval = 3000; // 设置重连间隔时间
this.maxReconnectAttempts = 5; // 最大重试次数
this.currentAttempt = 0;
this.init();
}
init() {
this.connect();
}
connect() {
try {
console.log('Attempting to establish a connection...');
this.ws = new WebSocket(this.url, this.protocols);
this.ws.onopen = () => {
console.log('Connection established');
this.resetRetries(); // 成功建立连接后重置尝试计数器
};
this.ws.onerror = (error) => {
console.error('Error occurred', error);
};
this.ws.onclose = () => {
if (this.shouldReconnect()) {
setTimeout(() => this.reconnect(), this.reconnectInterval); // 延迟一段时间后再尝试重连
}
};
} catch (e) {
console.error(e.message);
}
}
resetRetries() {
this.currentAttempt = 0;
}
shouldReconnect() {
return this.currentAttempt < this.maxReconnectAttempts;
}
reconnect() {
this.currentAttempt++;
console.warn(`Reconnecting attempt ${this.currentAttempt}`);
this.connect();
}
send(message) {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify(message));
} else {
console.error('Failed to send message because the socket is not open.');
}
}
close() {
if (this.ws) {
this.ws.close();
}
}
}
```
通过上述代码片段可以观察到,每当 WebSocket 关闭事件触发时都会检查是否应该执行重连操作[^1]。如果当前尝试次数小于最大允许的最大重试次数,则会启动定时器等待指定的时间之后再次调用 `connect()` 方法来尝试恢复连接。
#### 使用封装好的 WebSocket 类
接下来可以在页面组件或其他地方引入这个自定义的服务类,并初始化它以便于发送消息给服务器端:
```vue
<template>
<!-- 组件模板 -->
</template>
<script>
import WebSocketService from '@/utils/WebSocketService';
export default {
data() {
return {
wsService: null,
};
},
mounted() {
const URL = 'wss://example.com/socket'; // 替换成实际地址
this.wsService = new WebSocketService(URL);
// 发送测试消息至服务器
this.sendMessageToServer({ type: 'test' });
// 添加监听处理来自服务器的消息
this.listenForMessagesFromServer();
},
methods: {
sendMessageToServer(msg) {
this.wsService.send(msg);
},
listenForMessagesFromServer() {
this.wsService.ws.onmessage = function(event){
let receivedMsg = JSON.parse(event.data);
console.log(receivedMsg);
// 处理收到的数据...
};
}
},
beforeDestroy(){
this.wsService.close();
}
};
</script>
```
这段代码展示了如何实例化之前定义过的 `WebSocketService` 对象,并利用它的方法来进行消息传递和接收。注意这里还包含了生命周期钩子函数用于确保当组件销毁前关闭 Websocket 链接以释放资源。
阅读全文
相关推荐


















