How to use webSocket to update real-time weather in Vue

How to use webSocket to update real-time weather in Vue

Preface

Use webSocket in vue to make a simple weather real-time update module.

About webSocket operations and examples:

1.webSocket connection

insert image description here

2. Receive data

insert image description here

3. Reconnection mechanism

insert image description here

webSocket

1. About webSocket

WebSocket is a protocol provided by HTML5 that enables full-duplex communication over a single TCP connection. The browser sends a request to the server to establish a webSocket connection through JavaScript. After the connection is established, the client and server can directly exchange data through the TCP connection.

After you obtain the Web Socket connection, you can send data to the server through the send() method and receive the data returned by the server through the onmessage event.

var Socket = new webSocket(url, [protocol] );

protocol is optional and specifies acceptable subprotocols

2. Differences from AJAX Wheel

Nowadays, many websites use Ajax polling to implement push technology. Polling is when the browser sends an HTTP request to the server at a specific time interval (such as every 1 second), and the server then returns the latest data to the client's browser. This traditional model has an obvious disadvantage, that is, the browser needs to continuously send requests to the server. However, the HTTP request may contain a long header, of which the truly valid data may be only a small part. Obviously, this will waste a lot of bandwidth and other resources.

The webSocket protocol defined by HTML5 can better save server resources and bandwidth, and enable more real-time communication.

insert image description here

3.webSocket Events

insert image description here

4. A Simple Example

With the above brief introduction, let's create a webSocket instance and try it out:

function webSocketTest() {
    if ("webSocket" in window){
        alert("Your browser supports webSocket!");
        // Open a webSocket
        var ws = new webSocket("ws://localhost:8080/test");
        ws.onopen = function() {
            // WebSocket is connected, use the send() method to send data ws.send("send data");
            console.log("Data is being sent...");
        };
        
        ws.onmessage = function (evt) { 
            // Received data var data = evt.data;
            console.log("Data received...");
        };

        ws.onerror = function () {
            // Connection error console.log('Connection error...');
        }

        ws.onclose = function() { 
            // Close the webSocket
            console.log("Connection closed..."); 
        };
    } else {
        // The browser does not support webSocket
        alert("Your browser does not support webSocket!");
    }
}

As you can see, the use of webSocket is actually very simple:

1. Determine whether the browser supports webSocket;
2. Create a webSocket instance;
3. List the webSocket events and handle the corresponding business in the corresponding events.

The same method is used in Vue

Weather Update

Here we demonstrate the implementation of the real-time weather update effect mentioned earlier. The project framework is vue\element.

Basic code

<!-- Element used for layout, just use it directly -->
<el-popover
        placement="bottom"
        :title="weather.title"
        trigger="hover"
        :content="weather.cont">
    <div slot="reference" class="weather">
        <img :src="weather.url" alt="">
    </div>
</el-popover>
export default {
        data() {
            return {
                weather:
                    cityName: '',
                    title: '-- City / --℃',
                    cont: '--',
                    weatherCode: '0',
                    url: ''
                }
            }
        },
        methods: {
            // Get the weather async getTheWeather() {
                // First request the current weather conditions through the interface let res = await this.$Http.getWeather({});
                if(res.code === 200) {
                    // Here, put the weather data obtained by the interface into weather in data...

                    //Then open the websocket to receive in real time this.connectWebSocket();
                }
            },
            //websocket
            connectWebSocket () {
                let _this = this;
                if ("WebSocket" in window) {
                    console.log("Your browser supports WebSocket!");
                    // Open a webSocket
                    let url ='xxxxxxxxxxx'; // Provide you with the address for data push let ws = new webSocket(`ws://${url}`);
                    // Connection successful ws.onopen = function () {
                        // Web Socket is connected, use the send() method to send data ws.send("This is the test data sent");
                        console.log('Connection successful');
                    };
                    // Receive data for processing ws.onmessage = function (evt) {
                        let received_msg = evt.data;
                        // Here, put the weather data into data, and then the weather is updated...
                    };
                    // Connection error ws.onerror = function () {
                        console.log('Connection error...');
                    }
                    // Connection closed ws.onclose = function () {
                        // Close the websocket
                        console.log("Connection closed...");
                    }
                } else {
                    // The browser does not support WebSocket
                    console.log("Your browser does not support WebSocket!");
                }
            },

        },
        mounted() {
            // Get the local weather this.getTheWeather();
        }
    }

Picture material

It is best to discuss the weather code value with the backend for weather picture information, so that you can directly replace the value.

insert image description here

this.weather.url = require(`@/assets/img/weather/${weatherInfo.weatherCode}@2x.png`);

Reconnection mechanism

Finally, a reconnection mechanism is introduced.

Simple reconnection mechanism, just use setTimeout. When the connection error occurs/the connection is closed, use a timer to re-execute the connectWebSocket method to reconnect. However, there may be multiple problems with this operation, so a more elegant plug-in is found to reconnect - ReconnectingWebSocket.

ReconnectingWebSocket is actually an encapsulated webSocketTest instance with a reconnection mechanism. When the connection is disconnected, it will try to reconnect in a friendly way until it is reconnected. The usage is also relatively simple, just import and create it:

// Import import ReconnectingWebSocket from '@/util/ReconnectingWebSocket';

export default {
    data() {
        return {
            ...
        }
    },
    methods: {
        ...
        connectWebSocket() {
            let _this = this;
                if ("WebSocket" in window) {
                    console.log("Your browser supports WebSocket!");
                    // Open a webSocket
                    let url ='xxxxxxxxxxx'; // Provide you with the address for data push - let ws = new webSocket(`ws://${url}`); // Throw away + let ws = new ReconnectingWebSocket(`ws://${url}`); // Change to this // Connection successful ws.onopen = function () {
                        // Web Socket is connected, use the send() method to send data ws.send("This is the test data sent");
                        console.log('Connection successful');
                    };
                    // Receive data for processing ws.onmessage = function (evt) {
                        ...
                    };
                    // Connection error ws.onerror = function () {
                        console.log('Connection error...');
                    }
                    // Connection closed ws.onclose = function () {
                        // Close the websocket
                        console.log("Connection closed...");
                    }
                } else {
                    // The browser does not support WebSocket
                    console.log("Your browser does not support WebSocket!");
                }
        }
    }
}

ReconnectingWebSocket is a single JS file, which can be searched online.

This is the end of this article about how to use webSocket to update real-time weather in Vue. For more relevant content about updating real-time weather in Vue webSocket, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue uses WebSocket to simulate the chat function
  • Example analysis of how Vue uses websocket
  • The process of using SockJS to implement webSocket communication in vue
  • The correct way to use websocket in vue project

<<:  Combining insert and select to implement the method of "inserting the maximum value of a field in the database + 1"

>>:  Implementation process of nginx high availability cluster

Recommend

Explain how to analyze SQL efficiency

The Explain command is the first recommended comm...

Solution to web page confusion caused by web page FOUC problem

FOUC is Flash of Unstyled Content, abbreviated as ...

Introduction to MySQL statement comments

MySQL supports three types of comments: 1. From t...

JavaScript to achieve the effect of clicking on the submenu

This article shares the specific code of JavaScri...

Quickly solve the Chinese input method problem under Linux

Background: I'm working on asset reporting re...

What is the function and writing order of the a tag pseudo class

The role of the a tag pseudo-class: ":link&qu...

Detailed explanation of mysql5.6 master-slave setup and asynchronous issues

Table of contents 1. MySQL master-slave replicati...

Mini Program natively implements left-slide drawer menu

Table of contents WXS Response Event Plan A Page ...

The process of deploying a project to another host using Jenkins

environment Hostname ip address Serve Jenkins 192...

HTML markup language - table tag

Click here to return to the 123WORDPRESS.COM HTML ...

How to redirect to https through nginx load balancing

Copy the certificate and key on the web scp -rp -...

Build a file management system step by step with nginx+FastDFS

Table of contents 1. Introduction to FastDFS 1. I...

Detailed instructions for installing Jenkins on Ubuntu 16.04

1. Prerequisites JDK has been installed echo $PAT...

JS implements user registration interface function

This article example shares the specific code of ...