前要
今天公司用uniapp开发的手机端应用需要用到websocket实时获取数据,在这里记录一下使用方法,以及对于断开重连,心跳机制用法的封装。
使用方法
先上代码
1 2 3 4 5 6 7 8 9
| uni.connectSocket({ url: 'wss://www.example.com/socket' }); uni.onSocketOpen(function (res) { console.log('WebSocket连接已打开!'); }); uni.onSocketError(function (res) { console.log('WebSocket连接打开失败,请检查!'); });
|
使用uni.connectSocket()来进行连接,使用onSocketOpen和onSocketError来监听连接是否成功。
关于connectSocket()方法中的参数,具体请看官方介绍
- 其中complete参数,是接口调用结束之后的回掉,不管连接成功还是失败都会调用。
心跳机制,以及断开重连的封装使用
心跳机制是一种用于保持WebSocket连接的稳定性和活跃性的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| <template> <view> <button @tap="startWebSocket">连接 WebSocket</button> <button @tap="stopWebSocket">断开 WebSocket</button> </view> </template>
<script> export default { data() { return { socket: null, socketUrl: 'ws://*******', heartbeatInterval: 5000, reconnectInterval: 5000, isWebSocketOpen: false, }; }, methods: { startWebSocket() { this.socket = uni.connectSocket({ url: this.socketUrl, complete: () => { }, }); uni.onSocketOpen(res => { this.isWebSocketOpen = true; this.sendHeartbeat(); })
this.socket.onMessage((res) => { console.log('收到消息:', res.data);
});
this.socket.onClose(() => { console.log('WebSocket 已关闭');
this.isWebSocketOpen = false;
setTimeout(() => { this.startWebSocket(); }, this.reconnectInterval); }); }, stopWebSocket() { if (this.socket) { this.socket.close(); } }, sendHeartbeat() { if (this.isWebSocketOpen) { this.socket.send({ data: 'heartbeat', });
setInterval(() => { this.socket.send({ data: 'heartbeat', }); }, this.heartbeatInterval); } }, }, }; </script>
|
其他