关于在uniapp中使用websocket

关于在uniapp中使用websocket

DansRoh Lv4

前要

今天公司用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()来进行连接,使用onSocketOpenonSocketError来监听连接是否成功。

关于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, // 5秒发送一次心跳
reconnectInterval: 5000, // 5秒重连一次
isWebSocketOpen: false,
};
},
methods: {
startWebSocket() {
this.socket = uni.connectSocket({
url: this.socketUrl,
complete: () => {
},
});
uni.onSocketOpen(res => {
// 连接成功后设置状态
this.isWebSocketOpen = true;
// 发送心跳
this.sendHeartbeat();
})

// 监听 WebSocket 接收消息事件
this.socket.onMessage((res) => {
console.log('收到消息:', res.data);

// 处理收到的消息
});

// 监听 WebSocket 关闭事件
this.socket.onClose(() => {
console.log('WebSocket 已关闭');

// 设置状态
this.isWebSocketOpen = false;

// 5秒后重新连接
setTimeout(() => {
this.startWebSocket();
}, this.reconnectInterval);
});
},
stopWebSocket() {
if (this.socket) {
// 关闭 WebSocket 连接
this.socket.close();
}
},
sendHeartbeat() {
if (this.isWebSocketOpen) {
// 发送心跳消息
this.socket.send({
data: 'heartbeat',
});

// 定时发送心跳
setInterval(() => {
this.socket.send({
data: 'heartbeat',
});
}, this.heartbeatInterval);
}
},
},
};
</script>

其他

  • 标题: 关于在uniapp中使用websocket
  • 作者: DansRoh
  • 创建于 : 2023-12-28 00:00:00
  • 更新于 : 2024-06-24 17:16:49
  • 链接: https://blog.shinri.me/2023/12/28/12_uniapp中使用webscoket/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
关于在uniapp中使用websocket