uniapp中webscokcet的使用事项

1. 在mounted中调用方法

mounted() {
	this.$nextTick(() => {
		setTimeout(()=>{
			this.startCommunication()
		},300)
				
	}) 
			
},

2.在方法中开始连接websocket

startCommunication() {
                // 尝试 WebSocket连接
				this.socket = uni.connectSocket({
					url: "ws://xxx.xxx.x.xx:xxxx/地址", // 服务器地址
					success(data) {
						console.log("websocket连接成功");
					},
				})
				//监听 WebSocket 连接打开事件
				this.socket.onOpen(()=>{
					console.log('WebSocket连接已打开!');
					const data = {
						sendid: uni.getStorageSync("userId"), // 登录人的id
					};
					const data1 = JSON.stringify(data)
					// 通过 WebSocket 连接发送数据
					this.socket.send({
						data:data1
					})
				})
				//监听 WebSocket 接受到服务器的消息事件
				this.socket.onMessage((res)=>{
					console.log("收到消息了");
					if (res.data.indexOf("id") >= 0) {
							let obj = JSON.parse(res.data)
							// 提示弹框
							new Dialog().show({
								title: obj.Title,
								titleColor: '#e6a23c',
								confirmText: '确定',
								content: obj.Content,
								showCancel: true,
								confirm: () => {
									getMessage(obj.id).then(res => {
										if (res.data.data.message?.isOk) {
											uni.showToast({
												title: '已读',
												icon: "success",
											})
										} else {
											uni.showToast({
												title: '失败'
												icon: "error",
											})
										}
										
									})
								},
								cancel: () => {
									console.log("我取消了哦");
									
								}
							
							})
					}
				})
				// 监听 WebSocket 连接关闭事件
				this.socket.onClose(({code})=>{
					console.log("连接关闭事件",code);
				})
				// 监听 WebSocket 错误事件
				this.socket.onError((errMsg)=>{
					console.log(errMsg,'websocket发生错误');
                    // 连接出现错误后,可以进行重连
					this.reconnect()
				})
},
reconnect(){
				setTimeout(() => {
					this.startCommunication()
				},1000)
},

3.组件销毁时需要关闭websocket

beforeDestroy() {
	// 实例销毁,关闭socket
	this.socket.close()
},

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值