Websocket front-end connection and data reception

what is websocket

1. WebSocket is a network protocol used for full-duplex communication between clients and servers. It enables two-way communication over a single TCP connection, allowing the server to actively send data to the client, and the client to send data to the server. Unlike the traditional HTTP request-response model, WebSocket allows real-time communication, which can support real-time updating applications such as instant chat, online games, and stock market quotes.

2. The WebSocket protocol avoids the additional overhead and delay of HTTP requests by establishing a persistent connection. Clients can use the WebSocket API to establish a connection with the server and communicate by sending and receiving messages. WebSocket also supports advanced features such as heartbeat detection, data compression and expansion.

3. This article is about some operations performed on the large screen of visual data.

//webScoket初始化方法
	data(){
    
    
	return{
    
    
	websocket: {
    
    },//连接后端的地址(这里要替换成自己后端的连接地址)
	websocketUrl: 'ws://192.168.1.14:2000/',//判断是否重新连接
	lockReconnect: false,
	}
	}//自己在data  里面定义这些参数
			webScoketInit() {
    
    
				var that = this;
				that.websocket = new WebSocket(that.websocketUrl);
				//连接发生错误的回调方法
				that.websocket.onerror = function (event) {
    
    
					//尝试重新连接
					reconnect(that.websocketUrl);
					console.log(event);
					console.log('连接错误')
				};

				//连接成功建立的回调方法
				that.websocket.onopen = function (event) {
    
    
					//心跳检测重置
					heartCheck.reset().start();
					console.log(event,'成功数据');
					console.log('连接开启')
				}


				//接收到消息的回调方法
				that.websocket.onmessage = function (event) {
    
    
					//心跳检测重置
					let res = event.data
					//获取到后台发送的数据并转为json类型可转可不转 转了可能报错请根据自身情况修改
					//接收的后端返回数据
					console.log(res, '==============websocks')
			//进行业务处理 大数据可视化需要刷新页面
					if(res=="reload"){
    
    
						that.websk()
					}
					heartCheck.reset().start();
					
					
					
					
				}

				//连接关闭的回调方法
				that.websocket.onclose = function (event) {
    
    
					//尝试重新连接
					reconnect(that.websocketUrl);
					console.log(event);
					console.log('连接关闭')
				}

				//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
				window.onbeforeunload = function () {
    
    
					closeWebSocket();
				}

				//重新连接
				function reconnect(url) {
    
    
					if (that.lockReconnect) return;
					// console.log('连接成功')
					that.lockReconnect = true;
					//没连接上会一直重连,设置延迟避免请求过多
					setTimeout(function () {
    
    
						// that.websocket = new WebSocket(url);
						that.webScoketInit();
						that.lockReconnect = false;
						console.log('重连中')
					}, 2000);
				}

				//心跳检测
				var heartCheck = {
    
    
					//1分钟发一次心跳,时间设置小一点较好(50-60秒之间)
					timeout: 1000,
					timeoutObj: null,
					serverTimeoutObj: null,
					reset: function () {
    
    
						clearTimeout(this.timeoutObj);
						clearTimeout(this.serverTimeoutObj);
						return this;
					},
					start: function () {
    
    
						var self = this;
						this.timeoutObj = setTimeout(function () {
    
    
							//这里发送一个心跳,后端收到后,返回一个心跳消息,
							//onmessage拿到返回的心跳就说明连接正常
							that.websocket.send("ping"); //给服务器发送ping(可自定义与后端协调)
							//如果超过一定时间还没重置,说明后端主动断开了
							self.serverTimeoutObj = setTimeout(function () {
    
    
							//如果后端没回应就自动断开在从新连接
								console.log('重新连接')
								//如果onclose会执行reconnect,我们执行socket.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
								that.websocket.close();
							}, self.timeout)
						}, this.timeout)
					}
				}

				//关闭WebSocket连接
				function closeWebSocket() {
    
    
					that.websocket.close();
				}
			},

			websk() {
    
    
				window.location.reload()
			},

Success example diagram

insert description here

Guess you like

Origin blog.csdn.net/m0_62371223/article/details/131432106