Use webSocket in vue to update real-time weather

foreword

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

example

About the operation and examples of webSocket:

  1. webSocket connection

connect

  1. Receive data

Receive data

  1. Reconnection mechanism

Reconnection mechanism

webSocket

1. About webSocket

webSocket is a protocol provided by HTML5 for full-duplex communication on 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 the server can exchange data directly through the TCP connection.

After you get 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 the AJAX wheel

Now, in order to realize push technology, many websites use Ajax polling technology. Polling is at a specific time interval (such as every 1 second), the browser sends an HTTP request to the server, and then the server returns the latest data to the client's browser. This traditional mode brings obvious disadvantages, that is, the browser needs to continuously send requests to the server, but the HTTP request may contain a long header, and the real valid data may be only a small part, which is obviously a 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.

webSocket and AJAX polling

3. webSocket events

event

event handler

Remark

open

Socket.onopen

Triggered when a connection is established

message

Socket.onmessage

Triggered when the client receives data from the server

error

Socket.onerror

Triggered when a communication error occurs

close

Socket.onclose

Fired when the connection is closed

4. A simple example

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

function webSocketTest() {
    if ("webSocket" in window){
        alert("您的浏览器支持 webSocket!");
        // 打开一个 webSocket
        var ws = new webSocket("ws://localhost:8080/test");
        ws.onopen = function() {
            // webSocket 已连接上,使用 send() 方法发送数据
            ws.send("发送数据");
            console.log("数据发送中...");
        };
        
        ws.onmessage = function (evt) { 
            // 接收到的数据
            var data = evt.data;
            console.log("数据已接收...");
        };

        ws.onerror = function () {
            // 连接报错
            console.log('连接报错...');
        }

        ws.onclose = function() { 
            // 关闭 webSocket
            console.log("连接已关闭..."); 
        };
    } else {
        // 浏览器不支持 webSocket
        alert("您的浏览器不支持 webSocket!");
    }
}

It can be seen that the usage of webSocket is actually very simple:

  1. Determine whether the browser supports webSocket;
  2. Create a webSocket instance;
  3. Just list the webSocket events and process the corresponding business in the corresponding event.

The same method is used in vue

weather update

Here is a demonstration of the realization of the real-time weather update effect mentioned earlier. The project framework is vue\element.

base code

<!-- 布局 使用的element,直接使用即可 -->
<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>

copy

    export default {
        data() {
            return {
                weather: {
                    cityName: '',
                    title: '--市/--℃',
                    cont: '--',
                    weatherCode: '0',
                    url: ''
                }
            }
        },
        methods: {
            // 获取天气
            async getTheWeather() {
                // 先通过接口请求一次当前天气状况
                let res = await this.$Http.getWeather({});
                if(res.code === 200) {
                    // 这里将接口获取到的天气数据放入 data 中的 weather 中即可
                    ...

                    // 然后打开 websocket 实时接收
                    this.connectWebSocket();
                }
            },
            // websocket
            connectWebSocket (){
                let _this = this;
                if ("WebSocket" in window) {
                    console.log("浏览器支持 WebSocket!");
                    // 打开一个 webSocket
                    let url ='xxxxxxxxxxx'; // 给你提供数据推送的地址
                    let ws = new webSocket(`ws://${url}`);
                    // 连接成功
                    ws.onopen = function () {
                        // Web Socket 已连接上,使用 send() 方法发送数据
                        ws.send("这是发送的测试数据");
                        console.log('连接成功');
                    };
                    // 接收数据处理
                    ws.onmessage = function (evt) {
                        let received_msg = evt.data;
                        // 这里将天气数据放入 data,然后天气就更新了
                        ...
                    };
                    // 连接报错
                    ws.onerror = function () {
                        console.log('连接报错...');
                    }
                    // 连接关闭
                    ws.onclose = function () {
                        // 关闭 websocket
                        console.log("连接已关闭...");
                    }
                } else {
                    // 浏览器不支持 WebSocket
                    console.log("您的浏览器不支持 WebSocket!");
                }
            },

        },
        mounted() {
            // 获取当地天气
            this.getTheWeather();
        }
    }

Picture material

For weather picture information, it is best to discuss the weather code value with the backend, so that the value can be directly replaced and the job is over.

weather

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 directly. When a connection error is reported/connection is closed, use the timer to re-execute the connectWebSocket method to reconnect. But there may be many problems in this operation, so find a more elegant plug-in 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 connected. The method of use is also relatively simple, just import and create:

// 引入
import ReconnectingWebSocket from '@/util/ReconnectingWebSocket';

export default {
    data() {
        return {
            ...
        }
    },
    methods: {
        ...
        connectWebSocket() {
            let _this = this;
                if ("WebSocket" in window) {
                    console.log("浏览器支持 WebSocket!");
                    // 打开一个 webSocket
                    let url ='xxxxxxxxxxx'; // 给你提供数据推送的地址
-                   let ws = new webSocket(`ws://${url}`); // 扔掉
+                   let ws = new ReconnectingWebSocket(`ws://${url}`); // 改成这样
                    // 连接成功
                    ws.onopen = function () {
                        // Web Socket 已连接上,使用 send() 方法发送数据
                        ws.send("这是发送的测试数据");
                        console.log('连接成功');
                    };
                    // 接收数据处理
                    ws.onmessage = function (evt) {
                        ...
                    };
                    // 连接报错
                    ws.onerror = function () {
                        console.log('连接报错...');
                    }
                    // 连接关闭
                    ws.onclose = function () {
                        // 关闭 websocket
                        console.log("连接已关闭...");
                    }
                } else {
                    // 浏览器不支持 WebSocket
                    console.log("您的浏览器不支持 WebSocket!");
                }
        }
    }

}

ReconnectingWebSocket is a single JS file, just search online

Guess you like

Origin blog.csdn.net/love906897406/article/details/126513042