什么是WebSocket,以及如何在Python中使用它?
什么是WebSocket? (What is WebSocket?)
WebSocket is a communications protocol which provides a full-duplex communication channel over a single TCP connection. WebSocket protocol is standardized by the IETF as RFC 6455.
WebSocket是一種通信協(xié)議,可通過單個TCP連接提供全雙工通信通道。 WebSocket協(xié)議由IETF標(biāo)準(zhǔn)化為RFC 6455。
WebSocket and HTTP, both distinct and are located in layer 7 of the OSI model and depend on TCP at layer 4. RFC 6455 states that "WebSocket is designed to work over HTTP ports 80 and 443 as well as to support HTTP proxies and intermediaries", making it compatible with HTTP protocol. WebSocket handshake uses the HTTP Upgrade header to change from the HTTP to WebSocket protocol.
WebSocket和HTTP截然不同,位于OSI模型的第7層中,并在第4層上依賴于TCP。RFC 6455指出“ WebSocket設(shè)計為可通過HTTP端口80和443工作,并支持HTTP代理和中介” ,使其與HTTP協(xié)議兼容。 WebSocket握手使用HTTP升級標(biāo)頭將HTTP更改為WebSocket協(xié)議。
WebSocket protocol enables interaction between a web browser or any client application and a web server, facilitating the real-time data transfer from and to the server.
WebSocket協(xié)議支持Web瀏覽器或任何客戶端應(yīng)用程序與Web服務(wù)器之間的交互,從而促進(jìn)了服務(wù)器之間的實時數(shù)據(jù)傳輸。
Most of the newer version of browsers such as Google Chrome, IE, Firefox, Safari, and Opera support the WebSocket protocol.
大多數(shù)新版本的瀏覽器(例如Google Chrome,IE,Firefox,Safari和Opera)都支持WebSocket協(xié)議 。
Python WebSocket實現(xiàn) (Python WebSocket implementations)
There are multiple projects which provide either the implementations of web socket or provide with examples for the same.
有多個項目可以提供Web套接字的實現(xiàn),也可以提供示例。
Autobahn – uses Twisted and Asyncio to create the server-side components, while AutobahnJS provides client-side.
Autobahn –使用Twisted和Asyncio創(chuàng)建服務(wù)器端組件,而AutobahnJS提供客戶端。
Flask – SocketIO is a flask extension.
Flask – SocketIO是Flask的擴(kuò)展。
WebSocket –client provides low-level APIs for web sockets and works on both Python2 and Python3.
WebSocket –client提供了用于Web套接字的低級API,并且可以在Python2和Python3上使用。
Django Channels is built on top of WebSockets and useful in and easy to integrate the Django applications.
Django Channels構(gòu)建于WebSockets之上,在Django應(yīng)用程序中非常有用且易于集成。
使用WebSocket客戶端庫的Python應(yīng)用程序示例 (Python Example of application using WebSocket-client library)
The WebSocket client library is used to connect to a WebSocket server,
WebSocket客戶端庫用于連接到WebSocket服務(wù)器,
Prerequisites:
先決條件:
Install WebSocket client using pip within the virtual environment,
在虛擬環(huán)境中使用pip安裝WebSocket客戶端,
Create a virtual environment
創(chuàng)建一個虛擬環(huán)境
python3 -m venv /path/to/virtual/environment
python3 -m venv / path / to / virtual / environment
>> python3 -m venv venv
>> python3 -m venv venv
Source the virtual environment
采購虛擬環(huán)境
>> source venv/bin/activate
>>源venv / bin / activate
Install the websocket-client using pip
使用pip安裝websocket-client
>> (venv) pip3 install websocket_client
>>(venv)pip3安裝websocket_client
The below example is compatible with python3, and tries to connect to a web socket server.
以下示例與python3兼容,并嘗試連接到Web套接字服務(wù)器。
Example 1: Short lived connection
示例1:短暫的連接
from websocket import create_connectiondef short_lived_connection():ws = create_connection("ws://localhost:4040/")print("Sending 'Hello Server'...")ws.send("Hello, Server")print("Sent")print("Receiving...")result = ws.recv()print("Received '%s'" % result)ws.close()if __name__ == '__main__':short_lived_connection()Output
輸出量
Sending 'Hello, World'... Sent Receiving... Received 'hello world'The short lived connection, is useful when the client doesn't have to keep the session alive for ever and is used to send the data only at a given instant.
短暫的連接非常有用,當(dāng)客戶端不必使會話永遠(yuǎn)保持活動狀態(tài),并且僅用于在給定瞬間發(fā)送數(shù)據(jù)時。
Example 2: Long Lived connection
示例2:長期連接
import websocketdef on_message(ws, message):'''This method is invoked when ever the clientreceives any message from server'''print("received message as {}".format(message))ws.send("hello again")print("sending 'hello again'")def on_error(ws, error):'''This method is invoked when there is an error in connectivity'''print("received error as {}".format(error))def on_close(ws):'''This method is invoked when the connection between the client and server is closed'''print("Connection closed")def on_open(ws):'''This method is invoked as soon as the connection between client and server is opened and only for the first time'''ws.send("hello there")print("sent message on open")if __name__ == "__main__":websocket.enableTrace(True)ws = websocket.WebSocketApp("ws://localhost:4040/",on_message = on_message,on_error = on_error,on_close = on_close)ws.on_open = on_openws.run_forever()Output
輸出量
--- request header --- GET / HTTP/1.1 Upgrade: websocket Connection: Upgrade Host: localhost:4040 Origin: http://localhost:4040 Sec-WebSocket-Key: q0+vBfXgMvGGywjDaHZWiw== Sec-WebSocket-Version: 13----------------------- --- response header --- HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: /YqMq5iNGOMjtELPGCZsnozMSlw= Date: Sun, 15 Sep 2019 23:34:04 GMT Server: Python/3.7 websockets/8.0.2 ----------------------- send: b'\x81\x8b\xcb\xeaY.\xa3\x8f5B\xa4\xca-F\xae\x98TOP Interview Coding Problems/Challenges
Run-length encoding (find/print frequency of letters in a string)
Sort an array of 0's, 1's and 2's in linear time complexity
Checking Anagrams (check whether two string is anagrams or not)
Relative sorting algorithm
Finding subarray with given sum
Find the level in a binary tree with given sum K
Check whether a Binary Tree is BST (Binary Search Tree) or not
1[0]1 Pattern Count
Capitalize first and last letter of each word in a line
Print vertical sum of a binary tree
Print Boundary Sum of a Binary Tree
Reverse a single linked list
Greedy Strategy to solve major algorithm problems
Job sequencing problem
Root to leaf Path Sum
Exit Point in a Matrix
Find length of loop in a linked list
Toppers of Class
Print All Nodes that don't have Sibling
Transform to Sum Tree
Shortest Source to Destination Path
Comments and Discussions
Ad: Are you a blogger? Join our Blogging forum.
Please enable JavaScript to view the comments powered by Disqus.
翻譯自: https://www.includehelp.com/python/what-is-websocket-and-how-to-use-it-in-python.aspx
總結(jié)
以上是生活随笔為你收集整理的什么是WebSocket,以及如何在Python中使用它?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 线性代数向量乘法_标量乘法属性1 | 使
- 下一篇: 11个小技巧,玩转Spring!