Reprinted in ruan yifeng tutorial, just make a record, look at themselves.

People who are new to Websocket ask the same question: Why do we need another protocol when we already have HTTP, and what does it do for us?

The simple answer is that the HTTP protocol has a flaw: communication can only be initiated by the client.

For example, if we want to know about today’s day, only the client sends a request to the server, and the server returns the query result. HTTP protocol cannot make the server actively push information to the client. The nature of this one-way request makes it very difficult for the client to know if the server has continuous state changes. We can only use “polling” : every once in a while, we issue a query to see if the server has any new information. The most typical scenario is a chat room. Polling is inefficient and wasteful (because you have to keep linking, or HTTP links are always open). So, the project wondered if there was a better way, and that’s how WebSocket was invented.

The introduction of

——————————————————————————

WebSocket protocol was born in 2008, became an international standard in 2011, and is supported by all browsers. Its biggest characteristic is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.

Other features include:

  1. Based on TCP protocol, the implementation of the server side is relatively easy.

  2. It has good compatibility with HTTP, and the default ports are 80 and 443. HTTP is used in the handshake phase, so it is not easy to shield the handshake and can pass various HTTP proxy servers.

  3. Data visual comparison light, low performance overhead, efficient communication.

  4. You can send text or binary data

  5. There are no same-origin restrictions, and clients can communicate with any server

  6. The protocol id is WS (or WSS if encrypted), and the server URL is the URL.

    ws://example.com:80/some/path
    Copy the code

A simple example of a client

———————————————————————————-

The use of WebSocket is fairly simple

The following is an example of a web script that is basically easy to read

var ws = new WebSocket("wss://echo.websocket.rog"); ws.onopen= function(evt) { console.log('Connection open ..." ); ws.send('hello websocket! '); }; ws.onmessage = function (evt) { console.log("Received Message :" + evt.data); ws.close() }; ws.onclose = function () { console.log("connection closed."); };Copy the code

Client API

4.1 WebSocket Constructor

The WebSocket object is used as a constructor to create a new WebSocket instance

var ws = new WebSocket('ws://localhost:8080');
Copy the code

After executing the above statement, the client will connect to the server.

For a list of all properties and methods on the instance object, see here

4.2 the websocket. ReadyState

The readyState property returns the current state of the instance object, of which there are four types.

CLOSING: Indicates that the connection is being CLOSED. CLOSING: indicates that the connection is being CLOSED. If the value is 3, the connection fails to be openedCopy the code

Here is an example.

switch (ws.readyState) {
    case WebSocket.CONNECTING:
    //do someting
    break;
    case WebSocket.OPEN:
    // do something
    break;
    case WebSocket.CLOSING:
    //do something 
    break;
    case WebSocket.CLOSED:
    // do something
    break;
    default:
    // this never happens
    break;
}
Copy the code

4.3 the WebSocket. Onopen

The onopen property of the instance object, which specifies the callback function if the connection is successful.

ws.onopen = function (){ ws.send('hello server! '); }Copy the code

If you want to specify multiple callback functions, you can use the addEventListener method

ws.addEventListener('open',function(event){ ws.send('Hello Server!) ; })Copy the code

4.4 the WebSocket. Onclose

The onClose property of the instance object, which specifies the callback function if the connection is closed.

ws.onclose = function (event){
    var code = event.code;
    var reason = enevt.reason;
    var wasClean = event.wasClean;
    // handle close event 
}

ws.addEventListener('close',function (event) {
    var code = event.code;
    var reason = event.reason;
    var wasClean = event.wasClean;
    // handle close event
})
Copy the code

4.5 the webSocket. Onmessage

The onMessage property of the instance object, which specifies the callback function to receive data from the server

ws.onmessage = function (event){ var data = event.data; Ws.addeventlistener ('message',function(event){var data= event.data // handle data});Copy the code

Note that the server data can be textual or binary (bloB objects or Arraybuffer objects)

ws.onmessage = function (event){
    if(typeof event.data === String){
        console.log('Received data string!')
    }
    if (event.data instanceof ArrayBuffer){
        var buffer  = event.data
        console.log('Received arraybuffer');
    }
}
Copy the code

In addition to dynamically determining the data type received, you can also use the binaryType attribute to display the specified binary data type received

// Received bloB data ws. BinaryType = 'blob'; Ws.onmessage = function (e){console.log(e.data.size)} ws.onmessage = function(e){ console.log(e.data.byteLength); }Copy the code

4.6 the WebSocket. The send ()

The send () method of the instance object is used to send data to the server

Sends an array of text

Ws. Send (' your message);Copy the code

Sends a column of a BLOb object

var file = document.querySelector('input[type = "file"]').file[0]
ws.send(file)
Copy the code

4.7 the webSocket. BufferedAmount

The bufferedAmount property of the instance object, indicating how many bytes of binary data remain unsent, can be used to determine whether the sending is complete.

var data = new ArrayBuffer(1000000); Socket. send(data) if(socket.bufferedAmount === 0) {else {// Send is not finished}Copy the code

4.8 the webSocket. Onerror

The onError property of the instance object, which specifies the callback function when an error is reported

socket.onerror = function (event) { // handle error event } socket.addEventListener('error',function (event) { // handle  error event })Copy the code