【uniapp】uniapp中使用websocket

关于在uniapp中使用websocket有两种写法,一种是websocket,另一种是socketTask

在这里附上官网链接,官网对与socket的使用写的还是很详细的

websocket:https://uniapp.dcloud.net.cn/api/request/websocket.html

socketTask:uni-app官网

那么面对两种方式我们选择哪一种呢?

我个人的理解是:

如果你是在单页面使用且只有一个socket链接,那么使用websocket这种形式就可以

如果你在多页面有socket操作或者有多个socket链接,那么建议使用socketTask形式,这样不容易出错。

我自己使用的时候选择的是socketTask形式,附上代码:

//连接websocket
connectSocket() {
				let that = this;
				console.log('调用连接websocket')
				this.socketTask = uni.connectSocket({
						url: 'wss://x x x',
						success(res) {
							console.log("websocket连接成功");
							// that.isSuccess = true
						},
						fail(err) {
							console.log("报错", err);
						}
					},


				);
				this.socketTask.onOpen(function(res) {
					console.log('WebSocket连接已打开!');
					that.isSuccess = true
					that.getStatus()
					that.heart()
				})
				this.socketTask.onMessage(function(res) {
					console.log('收到服务器内容:' + res.data);
					that.handlerMsg(JSON.parse(res.data)) //这里是对获取到的数据进行操作
				});


				this.socketTask.onError(function(res) {
					console.log('WebSocket连接打开失败,请检查!');
					console.log(res);
					// this.isSuccess = false
					// that.connectSocket()

					//进入重新连接
					that.reconnect();

				})
				// // 监听连接关闭 -
				this.socketTask.onClose((e) => {
					console.log('WebSocket连接关闭!');
					clearInterval(that.timer)
					that.timer = ''
					if (!that.isClose) {
						that.reconnect()
					}
				})
				console.log(this.socketTask)
			},
//进入重新连接
			reconnect() {
				console.log('进入断线重连');
				// this.socketTask.close();
				this.socketTask = null;
				this.connectSocket()

			},
//发送消息
	sendSocketMessage(msg) {
				console.log('发送信息')
				console.log(msg)
				return new Promise((reslove, reject) => {
					this.socketTask.send({
						data: msg,
						success(res) {
							console.log('发送成功')
							reslove(res)
						},
						fail(res) {
							console.log('发送失败')
							console.log(res)
							reject(res)
						}
					});
				})

			},
			
//心跳
			heart() {
				let that = this;
				clearInterval(this.timer);
				this.timer = '';
				let msg = {
					"type": "heartbeat",
				}
				this.timer = setInterval(() => {
					 that.sendSocketMessage(JSON.stringify(msg)).then(res => {
						console.log('心跳成功')
					}).catch(res => {
						console.log('发送失败')
					console.log((res))
					 })

				}, 200000)
			},	

有这么几个注意点,

1 - 心跳时间的限制前后端商量好一个时间,心跳的存在是为了保证websocket一直处于一个链接状态,所以如果关闭socket以后记得清除心跳,不要造成内存泄露和浪费

2 - 重连这里可以设置一个标识表明什么情况下需要重新链接,什么情况下关闭链接,灵活使用

猜你喜欢

转载自blog.csdn.net/wuguidian1114/article/details/127492354
今日推荐