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

IIS7 IIS8 http automatically jumps to HTTPS (port 80 jumps to port 443)

IIS7 needs to confirm whether the "URL REWRI...

Example code for implementing dynamic skinning with vue+element

Sometimes the theme of a project cannot satisfy e...

Two methods to stretch the background image of a web page

There are two solutions: One is CSS, using backgro...

CentOS8 network card configuration file

1. Introduction CentOS8 system update, the new ve...

Introduction to the use of MySQL official performance testing tool mysqlslap

Table of contents Introduction Instructions Actua...

Practice of dynamically creating dialog according to file name in vue+el-element

Table of contents background accomplish 1. Encaps...

A brief discussion on the performance issues of MySQL paging limit

MySQL paging queries are usually implemented thro...

Detailed explanation of the MySQL MVCC mechanism principle

Table of contents What is MVCC Mysql lock and tra...

MySQL query optimization using custom variables

Table of contents Optimizing sorting queries Avoi...