Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the polling and principle of http and Websocket in html5?

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "what is the polling and principle of http and Websocket in html5", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this article "what is the polling and principle of http and Websocket in html5".

1. Polling of HTTP

The common communication mode between Web client and server based on Ajax (http) is divided into short connection and long polling.

Short connection: every time the client and server perform a HTTP operation, a connection is established, and the connection is interrupted at the end of the task.

Long polling: the client requests data from the server like traditional polling. However, if the server does not have data that can be returned to the client immediately, it does not immediately return an empty result, but keeps the request waiting for the data to arrive (or appropriate timeout: less than the ajax timeout), and then returns the data to the client as a result.

The long polling mechanism is shown in the following figure:

II. Basic concepts of Websocket

WebSocket is a protocol that HTML5 began to provide for full-duplex communication over a single TCP connection.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In WebSocket API, only one handshake is needed between the browser and the server, and a persistent connection can be directly created between the browser and the server for two-way data transmission.

In WebSocket API, the browser and the server only need to shake hands, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Now, in order to implement the push technology, many websites use Ajax polling. Polling is a browser in which the browser issues a HTTP request to the server at a specific time interval (such as every 1 second), and then the server returns the latest data to the client. This traditional mode brings obvious disadvantages, that is, browsers need to constantly send requests to the server, but HTTP requests may contain long headers, in which the really effective data may be only a small part, which will obviously waste a lot of bandwidth and other resources.

The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and can communicate in more real time.

The browser sends a request to the server to establish a WebSocket connection through JavaScript. After the connection is established, the client and the server can exchange data directly through the TCP connection.

When you get the Web Socket connection, you can send data to the server through the send () method and receive the data returned by the server through the onmessage event.

Third, Websocket handshake principle:

The handshake principle of Websocket can be roughly divided into the following steps:

Step 1: the client initiates a HTTP request connection

Step 2: the server takes the value of Sec-WebSocket-Key from the request header

Step 3: concatenate a magic_string to a new value for the Sec-WebSocket-Key value

Step 4: do sha1 encryption and then base64 encryption for the new value

Step 5: splice a response head

Step 6: the server sends the assembled response hair to the client

Step 7: the client decrypts Sec-WebSocket-Accept and gets Sec-WebSocket-Key to determine whether the handshake is successful.

Code implementation:

Address = sock.accept () # get the [handshake] information of the client data = conn.recv (1024) print (data) def get_headers (data): "take the value corresponding to Sec-WebSocket-Key from the request header and return" header_dict = {} header_str = data.decode ("utf8") for i in header_str.split (""): if str (I) .startswith ("Sec-") WebSocket-Key "): return i.split (": ") [1] .strip () # get the corresponding value ws_key = get_headers (data) # magic string magic string is: 258EAFA5-E914-47DA-95CA-C5AB0DC85B11magic_string = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'# splicing socket_str = ws_key + magic_string# sha1 encrypted socket _ str_sha1 = hashlib.sha1 (socket_str.encode ( Digest () # base64 encrypted sockets _ str_base64 = base64.b64encode (socket_str_sha1) # splicing response header response_tpl = "HTTP/1.1 101 Switching Protocols"Upgrade:websocket"Connection: Upgrade"Sec-WebSocket-Accept:% s"WebSocket-Location: ws://127.0.0.1: 9527 "% (socket_str_base64.decode (" utf8 ")) # Server sends response header to client conn.send (response_tpl.encode (" utf8 ")) # client server establishes persistent connection loop to receive and send data while True: msg = conn.recv (8096) print (msg) Title ws = new WebSocket (" ws://127.0.0.1:9527 ") Ws.onmessage = function (ev) {console.log (ev) / / for receiving data}

With the request header for the client to initiate the HTTP request:

B'GET / ws/ HTTP/1.1Host: 127.0.0.1:9527Connection: UpgradePragma: no-cacheCache-Control: no-cacheUser-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.3...Upgrade: websocketOrigin: http://localhost:63342Sec-WebSocket-Version: 13Accept-Encoding: gzip, deflate, brAccept-Language: zh-CN,zh;q=0.9Sec-WebSocket-Key: kJXuOKsrl3AR1KeFngRElQ==Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits'

4. The encryption and decryption methods of Websocket:

Decryption method:

# baccalaurex81x87x0exc3xf3xcdtersxf6xc6xf8mist5555555hashstr = baked x81x87x0exc3xf3xcdentxf6xc6xf8 Xf6xc6'# performs bit operations on the second byte, bits 9-16 of x87, with payload = hashstr [1] & 12 bits when the result is equal to 127. Then the 3rd-10th byte is the data length # 11th-14th byte is the string required for mask decryption # and the data is the 15th byte to the end if payload = 127th: extend_payload_len = hashstr [2:10] mask = hashstr [10:14] decoded = hashstr [14:] # when the result of the bit operation equals 126 Then the 3rd-4th byte is the data length # 5th-8th byte is the string required for mask decryption # and the data is the 9th to the end if payload = = 126: extend_payload_len = hashstr [2:4] mask = hashstr [4:8] decoded = hashstr [8:] # when the result of the bit operation is less than or equal to 125 Then this number is the length of the data # 3-6 bytes is the string required for mask decryption # and the data is the 7th byte to the end if payload send message var ws = null Function createsocket () {ws = new WebSocket ("ws://127.0.0.1:8001/ws"); ws.onmessage = function (data) {console.log ("message received from the server =", data.data);}} function send_msg () {var to_msg = document.getElementById ("msg") .value; ws.send (to_msg)}

Step 1: run flask

Step 2: run the html file

Step 3: click the create link

Step 4: enter a message

Step 5: click to send a message

Client .png

Server side. Png

In this way, we simply realize the client-server communication through the Websocket protocol. And we can create multiple links to communicate with the server at the same time.

Fifth, realize instant messaging (IM) based on Websocket:

Server code:

From flask import Flask, requestfrom geventwebsocket.websocket import WebSocketfrom gevent.pywsgi import WSGIServerfrom geventwebsocket.handler import WebSocketHandlerfrom geventwebsocket.exceptions import WebSocketErrorimport jsonapp = Flask (_ _ name__) user_socket_dict = {} @ app.route ("/ ws/") def websocket (username): # get the user's link user_socket = request.environ.get ("wsgi.websocket") # type:WebSocket user_socket_ links [us ername] = user_socket print (username+ "Link successful!") While True: msg = user_socket.receive () # accept the message for socket in user_socket_dict.values (): # type:WebSocket if user_socket! = socket:# do not reply to your own message server. Try: socket.send (json.dumps ({"sender": username) "msg": msg}) except: continueif _ _ name__ = ='_ _ main__': # enable Websocket service with specified address and port number http_serv = WSGIServer (("127.0.0.1", 8001), app, handler_class=WebSocketHandler) # start Websocket service http_serv.serve_forever ()

Html Code:

Title

Please enter your nickname:

Send a message

Var ws = null; var username = null; function createsocket () {username = document.getElementById ("username"). Value; ws = new WebSocket ("ws://127.0.0.1:8001/ws" + "/" + username); ws.onmessage = function (data) {var text_div = document.getElementById ("text_div"); var obj_data = JSON.parse (data.data) Var add_msg = "

"+ obj_data.sender +": "+ obj_data.msg +"

"; text_ div [XSS _ clean] + = add_msg;}} function send_msg () {var to_msg = document.getElementById (" msg "). Value; var text_div = document.getElementById (" text_div "); var add_msg ="+ to_msg +": "+ username +"

"; text_ div [XSS _ clean] + = add_msg; ws.send (to_msg);}

Step 1: run the flask server

Step 2: run the html file

Step 3: enter a nickname and click the create link

Step 4: enter a message

Step 5: click to send a message

The above is the content of this article on "what is the polling and principle of http and Websocket in html5". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more related knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report