Actual WebSocket framework Netty Netty learning + WebSocket currency exchange fire data acquisition projects

  Speaking WebSocket technology, in fact, comes from the server push technology, in reality, very often the required data is constantly changing, such as stock market data, chat software, and therefore a need for a client wants to get in real-time without refreshing the page server technology to the latest data, while the previous data acquisition is based on the client actively requests, the server returns the corresponding data. So there will be a server push technology.

  Server push mainly by the following: Ajax short polling, Ajax long polling, SSE, HTTP streaming, WebSocket.

First, the server push technology

  1, Ajax short polling

  Simple, the client (browser) time to send a request to the server to get the latest data. It can be achieved by triggering ajax request in a timer.

  Pros: implementation is very simple, JS end to make some changes can be, without any back-end service changes;

  Disadvantages: polling interval is too long, the user can cause the received data can not be timely updated; polling interval is too short, a query request will cause excessive increase in the burden on the server side.

          

   code show as below:

// every two seconds triggers a ajax request, obtain the latest data of 
the setInterval (function () {
    // do some ajax to here Wallpaper Call Retrieve Latest Data 
}, 2000);

  2, Ajax long polling

  Ajax on the basis of the polling made little improvement, when the rear end of the data is not updated in response to not return empty, but has been kept connected to the rear end, the rear end until the data changes, and closes the connection request to the corresponding distal end received data, once again initiate a request to the back-end, and process data just received.

  • The client initiates a request to the server (http request)
  • Server connection remains open until the data can be sent to the client, and then returns the requested (http response)
  • After the client receives the data returned by the server, processing data, and immediately initiate a new request
            

  advantage:

  • Can timely access to the latest data
  • Compared to the polling strategy to reduce the number of requests

  Disadvantages:

  Always connected to the server, can not be released, due to the limited number of connections that can be processed by a server, when the server reaches the upper limit of the processing, the server can not respond to new requests

  code show as below:   

function async() {
    $.ajax({
        url: 'http://api.3g.qq.com',
        success: function() {
            async();
            //success code
        }
    });
}

  Servlet3 in asynchronous tasks and DeferedResult Spring brings are using long connection Ajax.

  3、HTTP流

  HTTP streaming different from the polling and long polling method, it is within the client page life cycle, only need to use a HTTP connection, that is, only send a request to the server for this request, the server will keep the HTTP connection (not return response), and periodically sends data to the browser.
// Server side sample (NodeJS) 
the let = Express the require ( "Express" ); 
the let App = Express (); 

app.use (Express. Static ( "Resources" )); 
app.get ( "/ httpstream" , function ( REQ, RES) { 
    var X = 0 ; 
    res.setHeader ( 'Connection', 'Transfer-Encoding' ); 
  res.setHeader ( 'the Content-the Type', 'text / HTML; charset = UTF-. 8' ); 
  RES. setHeader ( 'transfer-encoding', 'chunked'); // declare a data transmission coding is chunked, let the browser timely processing 
    setInterval (function () { 
        res.write (the X- +++ "|");// every 2s last data transmission to the client
    },2000);
});

app.listen(3000);

  After the server receives the request, the client every two seconds to output a bit of text, but will not use res.end()or res.send()end the current http request.

// client sample JS 
var XHR = new new the XMLHttpRequest (); 
var Received = 0 ; 
var Result = "" ; 
xhr.open ( "GET", "/ httpstream", to true ); 
xhr.onreadystatechange = function () {
   IF (== xhr.readyState. 3) { // readyState. 3 represents the parsed data is 
    Result = xhr.responseText.substring (Received); // taken latest data 
    Received + = result.length; 
    the console.log (Result); 
  } 
} 
xhr.send ();
  With receives data from the server, the client readyState will periodically become 3 , responseText containing all data sources. By received previously recorded data length it has been treated, and then responseText taken latest data.
            

  advantage:

  Throughout the life cycle of the page, just create an http connection.

  Disadvantages:

  • If the access client too, because of the limited http server connection and is unable to service a new client.
  • Data received by the client flow will increase and may eventually lead to performance issues page

  4、SSE(Server-Sent-Events)

  SSE (Server-Sent Events) is an API to send data to the client based on a HTTP server implemented. He is an API for the realization of the above mentioned three methods (polling, long polling, HTTP streaming) is a standard. Use SSE API to create unidirectional connections to the server, the server may transmit any data via this connection. It has the following characteristics:

  • Disconnect connector
  • MIME type of server response must betext/event-stream
  • Need a browser API support (refer browser compatibility )

            

  Use as follows:

// client JS 
var = Source new new ; The EventSource (URL)
 // trigger connection is established 
source.onopen = function () {
   // do something here Wallpaper 
;}
 // trigger event receives from the server new 
source.onmessage = function (Event) { 
  var data = event.data; // server returns the data stored in the event.data 
};
 // connection exception is triggered 
source.onerror = function () {
   // do something here Wallpaper 
};

  The client creates a EventSource object bound to the corresponding url, then listening to the object onmessage event can get the latest data.

//server端示例(nodejs)
let express = require("express");
let app = express();

app.use(express.static("resources"));
app.get("/httpstream",function(req, res){
    var x = 0;
  res.writeHead(200, {
      "Content-Type":"text/event-stream",
      "Cache-Control":"no-cache",
      "Connection":"keep-alive"
    });
  //每个1s往客户端发送一条数据
  setInterval(function(){
      res.write("data: " + x++ + "\n\n");data transmission format must be "data: <Content> / n / n"//
  },1000);
});

app.listen(3000);

  5、WebSocket

  5.1 What is the WebSocket?

  WebSocket is html5 out of the agreement, http is why he did not persistent link, in fact, is a new WebSocket protocol to achieve the client and server with bi-directional text messages or binary data communication based; suitable for real-time data requirements are relatively strong scenes, such as instant messaging, live, share your desktop; the need to achieve a separate back-end; the client, not all browsers support.

  5.2、WebSocketCommunication protocol in two parts?

  • First, open HTTPhandshake negotiating connection parameters, before exchanging data, the client must negotiate appropriate parameters to establish a connection with the server
  • Second, a binary message framing mechanism (received message text and binary data transmission). WebSocketProtocol provides a number of powerful features: message-based communication, a custom binary framing layer, the sub-protocol negotiation, protocol extensions optional, and the like.

  5.3 What is the HTTP protocol upgrade?

  That is, first implemented by HTTP handshake, and then upgrade protocol, subsequent use WebSocket protocol.

  WebSocket and http protocols have some common ground, with front-end server to establish the connection websocket htt need to send a request and then requests data show that in the agreement need to upgrade to websocket. Application layer sec-websocket-key and sec-websocket-accept websocket identified with a unique channel.

                      

  As follows:

           

   Finally, after the handshake is completed, if the handshake is successful, the connection can be used as a bidirectional communication channel to exchange WebSocketmessages. This will not happen again between the client and server HTTPcommunications, everything from the WebSocket takeover agreement.  

  5.4 How to upgrade agreement

  WebSocket is upgraded by WebSocketServerHandshaker websocket protocol processing server-side.

          

        

  The pipeline is the essence of handshaker.handshake add codecs websocket agreement in the current and remove the http protocol codec.

   5.5, Websocket Message Entity -WebSocketFrame

  WebSocket message supports multiple entities, it may be used in different scenarios, such as text, binary data stream, heartbeat and the like. , The entity is implemented different message classes implement different messaging below.

  

  5.6 What is child WebSocket protocol -STOMP

  Directional text message protocol: TTMP predecessor STOMP protocol is protocol (a simple text-based protocol), designed specifically for messaging middleware. Its simplicity can happen to a message format definition webSocket the body. STOMP protocol have a lot of MQ support.

Two, WebSocket project combat exercise

  This project combat Bowen is a chat room, from the source code for college, GitHub address: https://github.com/kosamino/netty-websocket-server

   Code structure and functions as shown below:

              

  System flow chart as shown below:

  Attached Another blogger rest of WebSocket project combat: Netty + WebSocket currency exchange fire data acquisition projects

Guess you like

Origin www.cnblogs.com/jing99/p/12571980.html