WebSocket API and Server return data type judgment (file, binary data)

Source: Internet
Author: User

Why do I need WebSocket?

The first contact with WebSocket will ask the same question: we already have the HTTP protocol, why do we need another protocol? What benefits can it bring?

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

For example, we want to understand today's weather, only the client makes a request to the server, and the server returns the query results. The HTTP protocol does not make the server actively push information to the client.

The characteristics of this one-way request, doomed if the server has a continuous state change, the client to learn is very troublesome. We can only use polling: every once in a while, we send out a query to see if the server has any new information. The most typical scenario is a chat room.

Polling is inefficient and a waste of resources (because it must be connected, or the HTTP connection always turns on). So, engineers have been thinking, there's no better way. That's how WebSocket invented it.

Second, Introduction

The WebSocket agreement was born in 2008 and became an international standard in 2011. All browsers are already supported.

Its biggest feature is that the server can proactively push information to the client, the client can also actively send information to the server, is a true two-way equality dialogue, is a server push technology.

Other features include:

(1) based on the TCP protocol, the server-side implementation is relatively easy.

(2) Good compatibility with HTTP protocol. The default port is also 80 and 443, and the handshake phase uses the HTTP protocol, so the handshake is not easy to block, through a variety of HTTP proxy server.

(3) The data format is lighter, the performance overhead is small, and the communication is efficient.

(4) You can send text, or you can send binary data.

(5) The client can communicate with any server without the same origin limitation.

(6) The protocol identifier is ws (if encrypted wss ), the server URL is the URL.

WS://Example.com:80/some/path

Third, a simple example of the client

The use of WebSocket is quite simple.

Here is an example of a Web page script (click here to see the results of the operation), basically a glance to understand.

var New WebSocket ("wss://echo.websocket.org"function(evt) {   console.log ("Connection Open ...");   Ws.send ("Hello websockets!"  function(evt) {  "Received Message:" + evt.data);   function (evt) {  console.log ("Connection closed.") );};      
Iv. API for clients

The API for the WebSocket client is as follows.

4.1 WebSocket Constructors

The WebSocket object is used as a constructor for creating a new WebSocket instance.

    var New WebSocket (' ws://localhost:8080 ');

After executing the above statement, the client connects to the server.

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

4.2 websocket.readystate

readyStateproperty returns the current state of the instance object, in total four.

        Connecting: A value of 0 indicates that the connection is in progress.        OPEN: A value of 1 means that the connection is successful and communication is possible.        CLOSING: A value of 2 indicates that the connection is shutting down.        CLOSED: A value of 3 indicates that the connection has been closed or the connection failed to open.

The following is an example.

Switch(ws.readystate) { Casewebsocket.connecting://Do something     Break;  CaseWebsocket.open://Do something     Break;  Casewebsocket.closing://Do something     Break;  Casewebsocket.closed://Do something     Break; default:    //This never happens     Break;}
4.3 websocket.onopen

The property of onopen The instance object that specifies the callback function after the connection succeeds.

function () {  ws.send (' Hello server! ' );}

If you want to specify more than one callback addEventListener function, you can use the method.

function (event) {  ws.send (' Hello server! ') );});
4.4 Websocket.onclose

The property of onclose The instance object that specifies the callback function after the connection is closed.

Ws.onclose =function(event) {varCode =Event.code; varReason =Event.reason; varWasclean =Event.wasclean; //Handle Close Event};ws.addeventlistener ("Close",function(event) {varCode =Event.code; varReason =Event.reason; varWasclean =Event.wasclean; //Handle Close Event});
4.5 Websocket.onmessage

The property of onmessage The instance object that specifies the callback function after the server data is received.

function (event) {  var data = event.data;   // working with Data };ws.addeventlistener (function(event) {  var data = event.data;   //  processing Data });

Note that the server data may be text or binary data ( blob objects or Arraybuffer objects).

function (event) {  if(typeof Event.data = = = String) {    console.log ("Received data String ");  }   if instanceof ArrayBuffer) {    var buffer = event.data;    Console.log ("Received arraybuffer");}  }

In addition to dynamically judging the type of data you receive binaryType , you can also use attributes to explicitly specify the binary data type you receive.

// received is BLOB data Ws.binarytype = "blob"function(e) {  console.log (e.data.size);}; // received is ArrayBuffer data ws.binarytype = "ArrayBuffer"function(e) {  Console.log ( e.data.bytelength);};
4.6 Websocket.send ()

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

Example of sending text.

Ws.send (' your message ');

Example of sending a Blob object.

var file = document  . Queryselector (' input[type= "file"] ')  . files[0];ws.send (file);

Example of sending a ArrayBuffer object.

// sending canvas ImageData as ArrayBuffer var img = canvas_context.getimagedata (0, 0, +, +); var New Uint8array (img.data.length);  for (var i = 0; i < img.data.length; i++) {  = img.data[i];} Ws.send (binary.buffer);
4.7 Websocket.bufferedamount

The properties of bufferedAmount The instance object, indicating how many bytes of binary data are not sent out. It can be used to determine whether the send is over.

    var New ArrayBuffer (10000000);    Socket.send (data);     if (Socket.bufferedamount = = = 0)      {//  send completed    else  {       // send is not over    }
4.8 Websocket.onerror

The property of onerror The instance object that specifies the callback function at the time of the error.

function (event) {  //  handle Error event};socket.addeventlistener (function (event) {  //  handle Error Event});

This article originates from: http://www.ruanyifeng.com/blog/2017/05/websocket.html

WebSocket API and Server return data type judgment (file, binary data)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.