日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

什么是WebSocket,以及如何在Python中使用它?

發布時間:2025/3/11 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 什么是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是一種通信協議,可通過單個TCP連接提供全雙工通信通道。 WebSocket協議由IETF標準化為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設計為可通過HTTP端口80和443工作,并支持HTTP代理和中介” ,使其與HTTP協議兼容。 WebSocket握手使用HTTP升級標頭將HTTP更改為WebSocket協議。

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協議支持Web瀏覽器或任何客戶端應用程序與Web服務器之間的交互,從而促進了服務器之間的實時數據傳輸。

Most of the newer version of browsers such as Google Chrome, IE, Firefox, Safari, and Opera support the WebSocket protocol.

大多數新版本的瀏覽器(例如Google Chrome,IE,Firefox,Safari和Opera)都支持WebSocket協議 。

Python WebSocket實現 (Python WebSocket implementations)

There are multiple projects which provide either the implementations of web socket or provide with examples for the same.

有多個項目可以提供Web套接字的實現,也可以提供示例。

  • Autobahn – uses Twisted and Asyncio to create the server-side components, while AutobahnJS provides client-side.

    Autobahn –使用Twisted和Asyncio創建服務器端組件,而AutobahnJS提供客戶端。

  • Flask – SocketIO is a flask extension.

    Flask – SocketIO是Flask的擴展。

  • 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構建于WebSockets之上,在Django應用程序中非常有用且易于集成。

  • 使用WebSocket客戶端庫的Python應用程序示例 (Python Example of application using WebSocket-client library)

    The WebSocket client library is used to connect to a WebSocket server,

    WebSocket客戶端庫用于連接到WebSocket服務器,

    Prerequisites:

    先決條件:

    Install WebSocket client using pip within the virtual environment,

    在虛擬環境中使用pip安裝WebSocket客戶端,

    • Create a virtual environment

      創建一個虛擬環境

      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

      采購虛擬環境

      >> 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

    Collecting websocket_client==0.56.0 (from -r requirements.txt (line 1))Downloading https://files.pythonhosted.org/packages/29/19/44753eab1fdb50770ac69605527e8859468f3c0fd7dc5a76dd9c4dbd7906/websocket_client-0.56.0-py2.py3-none-any.whl (200kB)100% | | 204kB 2.7MB/s Collecting six (from websocket_client==0.56.0->-r requirements.txt (line 1))Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl Installing collected packages: six, websocket-client Successfully installed six-1.12.0 websocket-client-0.56.0

    The below example is compatible with python3, and tries to connect to a web socket server.

    以下示例與python3兼容,并嘗試連接到Web套接字服務器。

    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.

    短暫的連接非常有用,當客戶端不必使會話永遠保持活動狀態,并且僅用于在給定瞬間發送數據時。

    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\x98

    TOP 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

    總結

    以上是生活随笔為你收集整理的什么是WebSocket,以及如何在Python中使用它?的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。