uniapp中websocket的运用,含断线重连及心跳机制

intewl 发布于 uniapp

<template>
	<view>
		测试心跳
		<button type="primary" @click="open">打开</button>
		<button type="primary" @click="close">断开</button>
	</view>
</template>

<script>
	var num=3;
	var socketTask;
	var wsUrl ="ws://192.168.0.200:9084"; 
	var heartflag=false;//心跳开关
	var openflag=false;
	export default{
		data(){
			return{
				
			}
		},
		created() {
			this.websocket();
		},
		methods:{
			open(){
				if(openflag==false){
					
					this.websocket();
				}
			},
			close(){
				
				heartflag=true;
				socketTask.close()
				console.log('111')
			},
			websocket(){
				heartflag=false;
				socketTask =uni.connectSocket({
				    url:wsUrl, //仅为示例,并非真实接口地址。
					success:(e)=>{}
				});
				socketTask.onOpen(()=>{
					openflag=true;
					socketTask.send({data:res})
					this.sendMsg();
				})
				
				socketTask.onMessage(data=>{
					var data=JSON.parse(data.data)
					if(data){
						num=3;
					}
					console.log(data)
				})
				//websocket错误提示
				socketTask.onError(function(){
					console.log('错误')
					socketTask.close()
				})
				//websocket关闭提示
				socketTask.onClose(()=>{
				   console.log('关闭')
				   if(heartflag==false){
					   this.reconnect()
				   }
				   openflag=false;
				  
				});
			},
			reconnect(){
				setTimeout(()=>{
					this.websocket();
				},3000)
			},
			heart(){
				this.sendMsg();
			},
			sendMsg(){
				if(heartflag==true){return;}
				socketTask.send({data:'1234567890'})//此处为心跳包
				num--;
				if(num==0){
					num=3;
					socketTask.close()
				}else{
					console.log('心跳')
					setTimeout(()=>{
						this.heart()
					},3000)
				}
				
			}
		}
	}
</script>


2882浏览量 · 0评论 · 2020-01-09 02:40:35

全部评论  0

注册登录 进行评论

热门专题

更多专题