What is a Web Socket?

HTML5 began to provide a browser and server for full duplex communication network technology, belongs to the application layer protocol. It is based on the TCP transport protocol and reuses the HTTP handshake channel.

Why do I need a Web Socket

Because other methods, such as Ajax polling, are very resource-intensive, Web sockets were developed to solve this problem.

How to use the Web Socket

The principle of the landlord will not say, the following talk about my project to use the process and experience, is how to use the chat step by step. (Speak bad do not spray, the main is just a few months work front end meng new O(∩_∩)O, there is a wrong please comment guidance, thank you)

Method to connect to the Web Socket

Brief Description:

Connect to webSocket The WebSocket interface must be connected before sending messages to other users. Otherwise, you cannot receive messages sent to you.

The URL address of the connection request

Description:

Login is required the first time you connect to websocket. The way to log in is to send the user’s token.

Construct the following JSON string and send it to the server via websocket.

Assume that the current user’s token is 1212121 and the following information is sent:

‘{“type”:”login”,”identity”:”user”,”token”:”1212121″}’;

Pay attention to

The server will periodically send {“type”:”ping”}, when it receives a reply: {“type”:”pong”}, be sure to reply, otherwise the server will be disconnected, pay attention attention.

Either client or server can choose to send a ping to the other at any time after the handshake. When a ping message is received, the receiving party must reply to a Pong message as soon as possible. For example, you can use this method to ensure that the client is still connected.

Example of Websocket code

        var ws = new WebSocket("The request url");
        ws.onopen = function() {var MSG = "//"'{"type":"login","identity":"user","token":"2323422"}'; ws.send(msg); // Send messages to the server}; ws.onmessage =functionParse (evt) {var data = json.parse (evt.data);if (data.type && data.type == "ping") {
                ws.send('{"type":"pong"}'); // Send a message to the server}elseConsole. log(evt.data)}}; ws.onclose =function(evt) // Listener off {console.log("WebSocketClosed!");
        };
        ws.onerror = function(evt)// Listening error {console.log("WebSocketError!");
        };
Copy the code

If you cannot get the token, you can perform the following operations after logging in successfully. Reconnect after listening is closed

Ws. onClose(res =>{var ws = new WebSocket("The request url"); Ws.close () // Close the Web Socket and reconnect itCopy the code

Chat screen

For example, the chat interface is the News interface and all messages from other people are received by onMessage,

Do it in the else, send someone else’s message and push it into the array to re-render the interface, and then live chat is implemented.

//news
ws.onmessage = functionParse (evt) {var data = json.parse (evt.data);if (data.type && data.type == "ping") {
        ws.send('{"type":"pong"}');
    } elseConsole. log(evt.data) // handle it here}};Copy the code

Sending a message to someone requires some help from the background, which is very simple and I won’t go into details here.

So that’s the end of this article. Thank you for watching.

Ps: Record your learning journey O(∩_∩)O.