Code publish items (a) - take the initiative to implement the server to the client push messages (websocket)

So far, we have contacted to internal project are based on the HTTP protocol for communication: http link protocol is stateless, the client sends a request, the server returns a response, the server does not automatically send a message towards the client.

There are three ways to achieve server actively push messages to the client:

1 . Polling
 2 . Long polling
 3.websocket

polling

Low efficiency, the basic need

Let the browser sends a request timed towards the back end (secretly send data to the back-end through ajax), for example, send a request every five seconds, then your data may be delayed up to five seconds 

shortcomings 
  data delayed 
  consume excessive resources 
  request too many times

Long polling

Compatibility, general large companies will consider using it

# Queue + ajax 
server to each client to establish a queue, allowing the browser to the server via ajax towards data, to get their queue 
if there is no data will be blocked but would not have been blocked, such as blocking you 30 seconds, also no data is returned, and then let the client browser sends a request requesting the data again. 
Let the browser inside secretly obtain data towards the server, the client first came give each client to create a unique queue, after all ask for client requests data from its own corresponding queue, 
and the queue when there is no data, get method blocks will run once the data immediately, so we use patterns timeout argument add exception trapping to do basically zero delay
with respect to the polling basically no message delay of the number of requests to reduce the number
# Web and a micro-channel version of the qq are used in such a substantially logical

Ajax based polling function and long queues implemented (Django simple version of the chat room)

"" " 
1. Home custom user unique representation, each user initiates a queue 
2. Send button click event to bind data into back-end tell each queue 
3. Write code data automatically obtain ajax cycle call 
4. front-end data acquisition DOM manipulation to render the page 
. "" "

urls.py

# Based ajax + long polling queue implementation, the chat page 
URL (R & lt ' ^ ab_bl / ' , views.ab_bl),
 # front end to the rear end of the transmission information 
URL (R & lt ' ^ send_msg / ' , views.send_msg),
 # show the front end information 
URL (R & lt ' ^ get_msg / ' , views.get_msg),

ab_bl.html

<body> 
<h1 of> {{name}} IM </ h1 of> 
<P> 
  <INPUT type = " text " name = " Content " ID = " D2 " > 
  <Button ID = " D1 " > transmission </ button > 
</ P> 
<h1 of> chat </ h1 of> 
<div ID = " Content " > </ div> 

<Script> 
  // click the transmission trigger Ajax 
  $ ( ' # D1 ' ) .click (function () { 
      $ .ajax ({ 
          URL: '/ send_msg / ' , // messaging address, a rear end 
          type:' POST ' , 
          Data: { ' Content ' : $ ( ' # D2 ' ) .val ()}, // information passed to the backend 
          Success: function (Data) {   // the rear end to the front end of the return message 

          } 
      }) 
  }); 

  function a getMsg () { 
        $ .ajax ({ 
            URL: ' / get_msg / ' , 
            type: ' GET ' , 
            Data: { ' name ' : ' {{name}} ' }, // whenever the current login al data queue
            Success: function (args) {
                 // do the corresponding message returned for processing
                 IF (args.status) {
                     // news page is rendered into talk message chat records inside a global
                     @ 1 create a label 
                    var PELE = $ ( ' <P> ' );
                     // 2 to the label text is provided 
                    pEle.text (args.msg);
                     //. 3 speaks the created label to the label chats div 
                    $ ( ' #content ' ) .append (PELE) 
                } the else {
                     // no message it continues to send 
                }
                a getMsg ()   // cycle requests data 
            } 

        }) 
    } 
  $ (function () { 
      a getMsg ()   // page loaded automatically executed 
  })
 </ Script> 
</ body>

views.py

from django.shortcuts Import the render, the HttpResponse
 Import Queue
 from django.utils.httpwrappers Import jsonResponse
 # global Dictionary of 
q_dict = {}   # { 'represents a unique': queue, ....} 

DEF ab_bl (Request):
     # from the path name parameter passing for each user to make identification 
    name = request.GET.get ( ' name ' )
     # to each client to create a queue 
    q_dict [name] = Queue.Queue ()
     return the render (Request, ' ab_bl.html ' , about locals ()) 

# front end to the rear end of the message transmitted 
DEF send_msg (Request):
    IF request.method == ' the POST ' :
         # Get message sent by the user: ajax data in a data transfer 
        Content = request.POST.get ( ' Content ' )
         # pass the message to all queues 
        for Q in q_dict.values (): 
            q.put (Content) 
        return the HttpResponse ( ' OK ' ) 

# acquires data queue 
DEF get_msg (Request): 
    name = request.GET.get ( ' name ' )
     # get queue corresponding to 
    Q = q_dict.get (name)
     #Some stresses may be removed data queue and returned to the front end of the browser 

    # a dictionary definition ajax interact with 
    back_dic = { ' Status ' : True, ' MSG ' : '' }
     the try : 
        Data = q.get (timeout = 10)   # etc. 10s not directly given 
        back_dic [ ' MSG ' ] = Data
     the except queue.Empty AS E: 
        back_dic [ ' Status ' ] = False
     return jsonResponse (back_dic)

websocket

True to the server to send messages rather than passive transmission

Current mainstream browsers are supported websocket

HTTP protocol network protocol (non-encrypted transmission) 
HTTPS protocol network protocol (encrypted transmission) 
    above two agreements are short link 

websocket network protocol (encrypted transmission) 
    after the browser and server create links by default no longer disconnect 
    both ends can be based on the link to send and receive messages 
    birth websocket can truly server sends a message rather than passive transmission

websocket internal principle

Divided into two parts
     1 . Handshake link : Verify that the server supports websocket agreement 
        for the first time when access to the server (http-based protocol) browser generates a random string in the request header to send a copy to the server, leaving himself a parts 
        Sec -WebSocket-Key: ePW8kp1XqLNWbJxE / == Q38SA 
        server and the client doing the following random string of 
        
        random strings + Magic string splice 
        and spliced repeat encrypted result (SHA1 / Base64) to ciphertext
         
     server will produce ciphertext sent via response headers again to the client browser, the browser automatically are consistent than the parties to produce ciphertext, if consistent description of the service-side support websocket If they are not being given the assumption build websocket than on link based on the link to send and receive messages
2 . receives data transmitted in ciphertext >>> inevitably involve decryption (GHS) process based on data transmitted over the network are binary format corresponds to our python in bytes is the type of data decryption process . 1 . 7 after the message was received, to read the second byte data (payload) bytes to specify a different decryption process depending on the size of the data 7 = 127 : Later reading 8 words section = 126 : 2 bytes read later <= 125 : not read back to the data previously read and removed and then further read 4 bytes (Masking - Key) holding it back to parse the real data (based on a formula)

Code verification

The back-end code does not need to grasp the front end of the line

<! - just distal to write a single line of code -> 
<Script> 
    var ws = new new a WebSocket ( ' ws: //127.0.0.1: 22 is / ' )
 </ Script> 

! <- target point by ws send method to achieve the data exchange websocket ->

 

Guess you like

Origin www.cnblogs.com/wangcuican/p/12329850.html