current position:Home>Vue sets the global websocket and accepts message notification processing on the corresponding page

Vue sets the global websocket and accepts message notification processing on the corresponding page

2022-04-29 18:12:40inticaler

Recently, it has been useful in the project webSocket, Then, after receiving the message, you need to process it on different pages . All need to listen on different pages and carry out corresponding message processing .

First , stay app.vue Add socket initialization , And set the sending message , Processing of receiving messages and heartbeat detection .

// App.vue
export default {
	data() {
		return {
			// socket Parameters 
			socket: null,
			timeout: 10 * 1000, // 45 A second heartbeat 
			timeoutObj: null, //  Heartbeat countdown 
			serverTimeoutObj: null, //  Heartbeat countdown 
			timeoutnum: null, //  To break off   The countdown to reconnection 
			lockReconnect: false, //  prevent 
			websocket: null
		};
	},
    mounted() {
		this.initWebSocket(userId); // userId by socket The parameters of the link 
	},
    methods:{
        initWebSocket(supplierId) {
			// WebSocket It's different from the protocol used for ordinary requests ,ws Equate to http,wss Equate to https
			let wsUrl = `wss://192.168.1.33/rest/supplier-api/wss/websocket/${userId}`;
			this.websocket = new WebSocket(wsUrl);
			this.websocket.onopen = this.websocketonopen;
			this.websocket.onerror = this.websocketonerror;
			this.websocket.onmessage = this.setOnmessageMessage;
			this.websocket.onclose = this.websocketclose;
            //  Listen for window closing events , When the window closes , Active close websocket Connect , Prevent Windows from closing before the connection has been disconnected ,server The end throws an exception .
            // window.onbeforeunload = that.onbeforeunload
		},
		start() {
			console.log('start');
			// Clear the delayer 
			this.timeoutObj && clearTimeout(this.timeoutObj);
			this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
			this.timeoutObj = setTimeout(() => {
				if (this.websocket && this.websocket.readyState == 1) {
					this.websocket.send('heartBath');// Send a message , The server returns information , It means that the connection is good , Can be in socket Of onmessage Event reset heartbeat mechanism function 
				} else {
					this.reconnect();
				}
				// Define a delayer to wait for the server to respond , In case of overtime , Close the connection , Re request server establish socket Connect 
				this.serverTimeoutObj = setTimeout(() => {
					this.websocket.close();
				}, this.timeout)
			}, this.timeout)
		},
		reset() { //  Reset heartbeat 
			//  Clear time 
			clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
			//  Restart heartbeat 
			this.start();
		},
		//  Reconnect the 
        reconnect() {
			if (this.lockReconnect) return
			this.lockReconnect = true;
			// It's always reconnected if it's not connected , Set delay to avoid too many requests 
            this.timeoutnum && clearTimeout(this.timeoutnum);
            this.timeoutnum = setTimeout(() => {
				this.initWebSocket();
                this.lockReconnect = false;
            }, 5000)
        },
		async setOnmessageMessage(event) {
			console.log(event.data, ' Get the news ');
			this.reset();
			//  Customize global listening events 
			window.dispatchEvent(new CustomEvent('onmessageWS', {
				detail: {
					data: event.data
				}
			}))
			// // Find the news to enter      Start processing the front-end trigger logic 
			// if (event.data === 'success' || event.data === 'heartBath') return
        },
		websocketonopen() {
            // Turn on the heartbeat 
            this.start();
            console.log("WebSocket Successful connection !!!"+new Date()+"----"+this.websocket.readyState);
		},
		websocketonerror(e) {                
			console.log("WebSocket Connection error " + e);              
		},
		websocketclose(e) {
            this.websocket.close();
            console.log("WebSocket Connection is closed ");
		},
        websocketsend(messsage) {
            that.websocket.send(messsage)
        },
        closeWebSocket() { //  close websocket
            that.websocket.close()
        },
    }

among : After receiving the message, you need to customize a listening event , To allow the page to listen for message notifications .

async setOnmessageMessage(event) {
	console.log(event.data, ' Get the news ');
	this.reset();
	//  Customize global listening events 
	window.dispatchEvent(new CustomEvent('onmessageWS', {
		detail: {
			data: event.data
		}
	}))
	// // Find the news to enter      Start processing the front-end trigger logic 
	// if (event.data === 'success' || event.data === 'heartBath') return
},

Finally, add a listening event on the page you need to use

mounted () {
	//  add to socket Notification monitoring 
	window.addEventListener('onmessageWS', this.getSocketData)
},
methods: {
    //  Received message processing 
	getSocketData (res) {
		if (res.detail.data === 'success' || res.detail.data === 'heartBath') return
		// ... Business processing 
	},
}

thus ,vue Configure global socket Your needs are complete . Welcome to discuss

copyright notice
author[inticaler],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291637245329.html

Random recommended