WebSocket usage and how to use it in vue

Keywords: Javascript Front-end Vue.js websocket

WebSocket

WebSocket is a protocol for full duplex communication on a single TCP connection provided by HTML5.

WebSocket makes the data exchange between the client and the server easier, and allows the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake, and they can directly create a persistent connection and conduct two-way data transmission.

In the WebSocket API, the browser and server only need to shake hands, and then a fast channel is formed between the browser and the server. The two can directly transmit data to each other.

Now, in order to implement push technology, many websites use Ajax polling. Polling is to send an HTTP request to the server by the browser at a specific time interval (such as every 1 second), and then the server returns the latest data to the browser of the client. This traditional mode brings obvious disadvantages, that is, the browser needs to constantly send requests to the server. However, HTTP requests may contain long headers, in which the really effective data may be only a small part. Obviously, this will waste a lot of bandwidth and other resources.

The WebSocket protocol defined in HTML5 can better save server resources and bandwidth, and can communicate in real time.

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 exchange data directly through 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.

WebSocket instance

WebSocket protocol is essentially a TCP based protocol.

In order to establish a WebSocket connection, the client browser must first send an HTTP request to the server. This request is different from the normal HTTP request and contains some additional header information. The additional header information "Upgrade: WebSocket" indicates that this is an HTTP request for protocol upgrade, The server side parses these additional header information and then generates response information and returns it to the client side. The WebSocket connection between the client side and the server side is established. Both sides can freely transfer information through this connection channel, and the connection will continue until one of the client side or the server side actively closes the connection

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Rookie tutorial(runoob.com)</title>

        <script type="text/javascript">
            function WebSocketTest() {
                if ("WebSocket" in window) {
                    alert("Your browser supports WebSocket!")

                    // Open a web socket
                    var ws = new WebSocket("ws://localhost:9998/echo")

                    ws.onopen = function () {
                        // The Web Socket is connected. Use the send() method to send data
                        ws.send("send data")
                        alert("Data transmission in progress...")
                    }

                    ws.onmessage = function (evt) {
                        var received_msg = evt.data
                        alert("Data received...")
                    }

                    ws.onclose = function () {
                        // Close websocket
                        alert("Connection closed...")
                    }
                } else {
                    // The browser does not support WebSocket
                    alert("Your browser does not support WebSocket!")
                }
            }
        </script>
    </head>
    <body>
        <div id="sse">
            <a href="javascript:WebSocketTest()">function WebSocket</a>
        </div>
    </body>
</html>

Introduction to socket.io

socket.io is a class library with WebSocket encapsulated inside, which can establish real-time communication between browser and server.

If some older browsers do not support WebSocket, socket.io uses polling instead. In addition, it also has the characteristics of sending binary messages, multiplexing and creating rooms. Therefore, socket.io is a better choice than using the native WebSocket directly.

Developing a real-time application is mainly divided into two parts: server and client. socket.io provides corresponding npm packages for us to call conveniently.

Next, we will introduce the two blocks through a vivid and interesting chestnut.

Now suppose Li Bai, Zhang San, Li Si and Wang Wu join a room called chess and card room. At the end of the article, we will have an online chat room with sparrows, although small and dirty.

Client api

npm i socket.io-client  //Install the npm package provided by socket.io for the client

  • Next, you can establish a connection to the server on the page
import io from "socket.io-client"

const socket = io("http://127.0.0.1:3001 ") / / establish connection

  • Send message to server
const socket = io("http://127.0.0.1:3001")
socket.emit("talk", "Hurry up, it's getting dark")

  • Receive information from the server
const socket = io("http://127.0.0.1:3001")
socket.on("talk", (data) => {
    console.log(data) //Print data
})

  • Seeing Yao's news, Li Bai tried to resist the impulse to greet each other's family and said like coaxing them:
const socket = io("http://127.0.0.1:3001")
socket.on("talk", (data) => {
    socket.emit("talk", "What dare you do!")
})

The functions of the client are basically developed. The core APIs are on and emit, which are simple and elegant for sending and receiving messages.

Posted by JaGeK on Wed, 03 Nov 2021 18:12:36 -0700