Reprinted -WebSocket protocol analysis

Now, many sites in order to achieve push technology, the technology used is polling. Polling refers to specific time intervals (e.g., every second), it sends an HTTP request to the server by the browser, and returns the data to the browser by the server
. Since the HTTP protocol is inert, only the client initiated the request, the server will return data. Prerequisites polling technology is also based on this mechanism. WebSocket belonging to the service side push technology, is essentially an application layer protocol, full-duplex bidirectional communication can be realized persistent connections. Before introducing WebSocket, to talk about polling techniques and HTTP streaming technology.

Article Directory

  • Traditional polling technique: Ajax short polling
  • Comet
    • Ajax long polling
    • HTTP流
  • HTML5 implement server push
    • SSE
    • WebSocket

Ajax short polling (Ajax Polling)

Ajax client that is short polling periodically sends an HTTP request to the server, regardless of whether the server actually get to the data, the response will be returned to the client. Each corresponds to a request Response, because of HTTP / 1.1 persistent connection (once established TCP connection, sending multiple requests) and pipelining techniques (asynchronous transmission request), so that the HTTP request may initiate multiple asynchronous requests to establish a TCP connection after .

 

 

This traditional model brings obvious disadvantages, i.e., the need to constantly browser request to the server, but each time the HTTP request will bring long transmission request header field, wherein data may only be truly effective is small fraction (such as Cookie field), the server will obviously wasting bandwidth and other resources.

A friend might think that Ajax can increase the transmission time, such as for a period of 3s instead. But a long time, relatively high real-time requirements for projects, the page will update the data too slow.

Comet (server push)

The relatively new technology for data acquisition to the server is polling Comet, a service-side push. Simply put, after the server is to push the client sends an HTTP request, the server can proactively push data to the client . Comet achieved in two ways: Ajax long polling and HTTP streaming.

Ajax long polling (Ajax Long-polling)

Ajax long polling itself is not a real push. Polling is a variant of the long short polling. After an HTTP request to the server on the client, the server does not always respond immediately: When the server gets the latest data, the data will be transmitted to the client terminal; when the data is not updated, the server will maintain this connection, after waiting for the update data, before end of the transmission of data to the client. Of course, if the server data is not updated for a long time, after a period of time, the request will time out. After the client receives the timeout message will resend an HTTP request to the server.

That is, only get updated data on the server, the data will be transmitted to the client. This way there are also disadvantages. Although the server can take the initiative to transmit data to the client, but still need to issue a request (HTTP request much less than the number of short polling) repeatedly.

 

Short and long polling polling the same point that the client needs to initiate an HTTP request to the server, differs in how the server response: immediate short polling response server, regardless of whether the data is valid; the data update is to wait long polling response .

HTTP流

Unlike HTTP streaming polling techniques, the HTTP streaming to establish a TCP connection only once , after the HTTP communication 3-way handshake, then the client initiates an HTTP request to the server, and the server keep the connection open, periodically transmit data to the client . The two sides in the absence of clearly disconnected from the server to the client will continue to transmit data. In other words, if the data is not updated server, the server does not return a response, but remain connected; if the data is updated, it will immediately transmit the data to the client. At this time will initiate an HTTP request, the process again and again.

In JS, 3 can be achieved if the HTTP streaming readystatechange event listener and a value detected of readyState. With the data received from the server, periodically readyState value becomes 3. When the value becomes readyState 3, responseText property will save all the data received. At this point, we need to compare the data previously received, decided to start to get the latest data from any location. HTTP streaming manner by XHR object as follows:

let httpStream = (url, processor, finished) => {
  let xhr = new XMLHttpRequest()
  let received = 0
  xhr.open(url, 'get', true)
  xhr.addEvetntListener('readystatechange', () => {
    let result
    if (xhr.readyState === 3) {
      result = xhr.responseText.slice(received)
      received += result.length
      processor(result)
    } else if (xhr.readyState === 4) {
      finished(xhr.responseText)
    }
  })
}

As long as readyState is 3, then separated to responseText to get the latest data. received here indicates how many records have been processed characters. The latest data is then processed by the processor callback function. When readyState is 4, data representing completely acquired, it is passed directly to the xhr.responseText callback processing may be finished.

Call as follows.

httpStream(url, data => {
  console.log(data)
}, finishedData => {
  console.log(data)
})

For (long and short) polling and HTTP streaming to do a little summary

  1. Traditional polling technique (Ajax polling short) is a client sends an HTTP request to the server, regardless of whether the data is updated, the server will transmit data . A request corresponds to a response.
  2. Server Push technology (Ajax long polling) is short polling variant, the client sends an HTTP request to the server, only to wait until after the data update data transmission, otherwise the server remains connected . Then initiates the next HTTP request, a request corresponding to a response.
  3. Server push (HTTP streaming), the client initiates an HTTP request only once, the state connected to the server , after the data update, the server will transmit the data, or remain connected. At this time, corresponding to a plurality of requset response.
  4. Whether short polling, long polling, or HTTP stream, in that the same are required to initiate an HTTP request to the client .

HTML5 implement server push

Because of the importance of server push (to achieve results update events, chat rooms, etc.), HTML5 server-side push to achieve the two interfaces, SSE and WebSocket.

SSE

SSE (Server-Sent Eevents, the server sends an event) is used to create a one-way connection to the server, the server may transmit any number of data via this connection. SSE has achieved the following requirements

  1. MIME type of server response must be text / event-stream.
  2. You must be in accordance with the specified output format.

Usage is as follows, in fact, understand the server push after, SSE relatively simple to use

// EventSource accepted parameters must be homologous.
// use the event listener message messages received from the server and stored in event.data object.
let source = new EventSource('index.php')
source.onmessage = e => {
  console.log(e.data)
}

SSE is not supported in IE, ios4.0 above, android4.4 more support SSE.

 

WebSocket

Paving the way for so long previously, and finally to the WebSocket ... :) thank all our friends do not mind the patience to read.

Briefly, a WebSocket is a protocol with HTTP protocol as the application layer, are a subset of TCP / IP protocol. HTTP protocol is one-way communication protocol, only the client sends an HTTP request, the server will return data. The WebSocket protocol is a two-way communication protocol, after a connection is established, the client and the server can take the initiative to send or receive data to each other. WebSocket protocol established premise needs the HTTP protocol, after a connection is established, two-way communication on a persistent connection has nothing to do with the HTTP protocol.

WebSocket protocol goal is to provide full-duplex bidirectional communication in a separate persistent connection. The client and server can take the initiative to send and receive data to each other. After you create a WebSocket in JS, there will be a HTTP request is sent to the browser to initiate a request. After obtaining the server responds to establish a connection using HTTP upgrade will convert the HTTP protocol WebSocket protocol. That is, using the standard HTTP protocol can not be achieved WebSocket, only support those browsers specialized protocols to work properly.

Please read carefully, remember the above paragraph. :)

Since WebScoket uses a custom protocol, so the URL with HTTP protocol is slightly different. Unencrypted connection ws: //, instead of http: //. Encrypted connection wss: //, instead of https: //.

JavaScript is achieved using relatively simple WebScoket agreement, the following are WebSocket APIs

// open WebSocket, url parameters passed no limit same-origin policy.
let websocket = new WebSocket(url)

// Listen open event, send a plain text string data (if the object must be serialized.) When the url successfully established websocket.
websocket.onopen = () => {
  if (websocket.readyState === WebSocket.OPEN) {
    websocket.send('hello world')
  }
}

// Listen message event, to accept the data when the server response. The returned data is stored in the event object.
websocket.onmessage = e => {
  let data = e.data
  console.log(data)
}

// Listen for the error event, triggered when an error occurs, the connection can not be sustained.
websocket.onerror = () => {
  console.log('websocket connecting error!!')
}

// listen for close event, triggered when the connection is closed. Only the event object close events have additional information. You can view this information off
websocket.onclose = e => {
  let clean = e.wasClean // are shut
  let code = e.code // server returns a status code value.
  let reason = e.reason // message returned by the server.
}

Note, WebScoket syntax is not supported DOM2 event binding event handlers, so you must use DOM0 level syntax to bind the event handler for each event.

// correct!
websocket.onerror = () => {}
// error!
websocket.addEventListener('error', () => {})

WebSocket is an application layer protocol that is a subset of the TCP / IP protocol, handshaking status code 101 by the HTTP / 1.1 protocol. In other words, the need to establish the WebSocket protocol by means of HTTP protocol, then returned 101 status code on the server, you can websocket full duplex two-way communication, and no matter what the HTTP protocol .

Reference wiki example handshake protocol: and some of the fields will be explained.

 

Connection: Connection must be set to Upgrade, it indicates that the client wishes to connect to upgrade

Upgrade: Upgrade must be set to WebSocket, after obtaining the express server response, use HTTP to upgrade the HTTP protocol conversion (upgrade) for the WebSocket protocol.

Sec-WebSocket-key: a random string, it is used to verify the protocol is not HTTP protocol WebSocket protocol

Sec-WebSocket-Version: indication of which version WebSocket.

Sec-WebSocket-Accept: calculated Sec-WebSocket-Accept and special string. Verify whether the agreement is WebSocket protocol.

Sec-WebSocket-Location: the Host field, and it shows an address request WebSocket protocol.

The HTTP / 1.1 101 Switching Protocols: 101 status code indicates that the upgrade protocol, after returning a status code 101, HTTP protocol to complete the work, is converted to the WebSocket protocol. Then it can be a full-duplex two-way communication.

Browser compatibility better WebSocket protocol.

 

转载地址:https://www.cnblogs.com/unclekeith/p/8087182.html

 

Guess you like

Origin www.cnblogs.com/shen-qiang/p/11934567.html