HTML5 WebSocket protocol in-depth understanding of

1. Background

  Many sites in order to achieve push technology, the technology used is Ajax polling . Polling is emitted in a specific interval of time by the browser HTTP request to the server, and the latest data is returned by the server to the client browser. This traditional model brings obvious disadvantage that the browser requires constant request to the server, however, HTTP requests may contain a long head, which truly effective data may only be a small part, obviously this will waste a lot of bandwidth resources. HTML5 add some of the new agreement the WebSocket , can be provided on a single TCP connection provides full-duplex, two-way communication , can save server resources and bandwidth, and can communicate in real time.

2, WebSocket Introduction

  Traditional http is a protocol, WebSocket is a protocol, http server can not be achieved using WebSocket,

2.1 Browser Support for

The basic mainstream browsers support

2.2 Advantages

Http respect to the following benefits:

  • 1. The client and server only establish a TCP connection, you can use fewer connections.
  • 2.WebSocket server can take the initiative to push data to the client, more flexible and efficient.
  • 3. More lightweight protocol header, the data transfer amount reduced.

Contrast in rotation mechanism

3, WebSocket usage

  We understand what WebSocket so, what advantages are after, how to use it?

Creating 3.1.WebSocket

WebSocket uses a custom protocol, url http mode with slightly different, unencrypted connection is ws: //, encrypted connection is wss: //, WebSocket instance new WebSocket()to create a method,

var ws = new WebSocket(url, [protocol] );

The first parameter url, specify the URL connection. The second parameter is optional protocol, the sub-protocol specified acceptable.

3.2.WebSocket property

When the object is created ws, ws is the readyState instance state, a total of four states

  • 0 indicates that the connection has not been established.

  • 1 indicates that the connection has been established, you can communicate.

  • 2 represents an ongoing connection closed.

  • 3 indicates that the connection has been closed or the connection can not be opened.

Tips: before sending the message to determine the state, there should also be disconnected reconnection mechanism.

3.3.WebSocket event

After you create an object ws instance, you will have the following events, you can write event callback method in accordance with different states.

  • Triggered when the connection is established ws.onopen

  • ws.onmessage trigger client-side server receives data

  • Triggered when an error occurs ws.onerror communication

  • Triggered when the connection is closed ws.onclose

ws.onmessage = (res) => {
  console.log(res.data);
};

ws.onopen = () => {
  console.log('OPEN...');
};

ws.onclose=()=>{
 console.log('CLOSE...');
}

3.4.WebSocket method

  • ws.send () used to send data (plain text data transmission only)

  • ws.close () closes the connection

4, Demo demo

  Knowing some of the API WebSocket, and build on the progress, do a little bit run case.

4.1.Node server

WebSocket protocol and Node together with a very good, for two reasons:

1.WebSocket client event-based programming and Node custom event almost.

2.WebSocket achieve the client and server-side long connection, Node basic event-driven manner is very suitable for high concurrent connections

Create a webSocket.js as follows:

const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({ port: 8080 });
wss.on('connection', function (ws) {
    console.log('client connected');
    ws.on('message', function (message) {
        ws.send('我收到了' + message);
    });
});

Open the windows command window, run

4.2.HTML client

Create a new index.html page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>webSocket小Demo</title>
</head>
<body>
    <div class="container">
        <div>
            <input type="text" id="msg">
            <button onclick="sendMsg()">发送报文</button>
        </div>
    </div>
    <script>
        const ws = new WebSocket('ws://localhost:8080');
        ws.onmessage = (res) => {
            console.log(res);
        };
        ws.onopen = () => {
            console.log('OPEN...');
        };
        ws.onclose = () => {
            console.log('CLOSE...');
        }
        function sendMsg() {
            let msg = document.getElementById('msg').value;
            ws.send(msg);
        }
    </script>
</body>

Open your browser in order to enter characters 1,2,3, click Send report each time you have finished entering the body, showing us back to the messages in the event of res.data in ws.onmessage

5, the problem with summary

  Above simply describes the use of a simple API WebSocket in the concurrent treatment of high and long connecting these requirements, such as chat rooms, WebSocket http request may be more appropriate and efficient.

   However, other problems found easily disconnect during use WebSocket, it is determined whether to disconnect before each packet transmission, when the transmission packet a plurality of times, due to the different amounts of data returned from the server, the client returns before and after the order may different, so it is necessary in the client receives a message on the next return data and then send a message, in order to avoid excessive nested callbacks, solved by a synchronous manner Promise, async, await and so on. About WebSocket write so, if insufficient, welcome to correct me!

Guess you like

Origin www.linuxidc.com/Linux/2019-11/161492.htm