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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

如何使用Tornado实现WebSocket服务器?

發布時間:2025/3/11 编程问答 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何使用Tornado实现WebSocket服务器? 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

什么是龍卷風? (What is Tornado?)

Tornado is a python web framework and asynchronous networking library. It is scalable and non-blocking. It specializes in dealing with event-driven networking. As tornado supports concurrent connections, naturally, a server can take advantage of this behavior and handle a lot of web socket connections within a single node.

Tornado是一個python Web框架和異步網絡庫 。 它具有可伸縮性和非阻塞性。 它專門處理事件驅動的網絡。 由于龍卷風支持并發連接,自然地,服務器可以利用此行為并在單個節點內處理許多Web套接字連接。

什么是Websocket? (What is Websocket?)

WebSocket is a protocol that provides full-duplex communication channels over a single TCP connection. The behavior of the open socket makes a web connection stateless and facilitates the real-time data transfer to and from the server.

WebSocket是一種協議,可通過單個TCP連接提供全雙工通信通道。 開放套接字的行為使Web連接變為無狀態,并促進了與服務器之間的實時數據傳輸。

WebSockets are designed to be used in web-browsers and servers. A connection is opened once and messages can travel to-fro multiple times before the connection is closed.

WebSockets設計用于Web瀏覽器和服務器。 連接一次打開,并且消息可以在關閉連接之前往返傳輸多次。

安裝龍卷風 (Install Tornado)

Installing the tornado is rather simple in a virtual environment using pip.

在使用pip的虛擬環境中安裝龍卷風非常簡單。

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

    >>(Venv)pip3安裝龍卷風

Using cached https://files.pythonhosted.org/packages/30/78/2d2823598496127b21423baffaa186b668f73cd91887fcef78b6eade136b/tornado-6.0.3.tar.gz Requirement already satisfied: six in ./venv/lib/python3.7/site-packages (from websocket_client==0.56.0->-r requirements.txt (line 1)) (1.12.0) Installing collected packages: tornadoRunning setup.py install for tornado ... done Successfully installed tornado-6.0.3

使用Tornado庫啟動Web套接字服務器的Python示例 (Python example to start a web socket server using Tornado library)

'''This module hosts a websocket server using tornadolibraries '''import tornado.web import tornado.httpserver import tornado.ioloop import tornado.websocket as ws from tornado.options import define, options import timedefine('port', default=4041, help='port to listen on')class web_socket_handler(ws.WebSocketHandler):'''This class handles the websocket channel'''@classmethoddef route_urls(cls):return [(r'/',cls, {}),]def simple_init(self):self.last = time.time()self.stop = Falsedef open(self):'''client opens a connection'''self.simple_init()print("New client connected")self.write_message("You are connected")def on_message(self, message):'''Message received on the handler'''print("received message {}".format(message))self.write_message("You said {}".format(message))self.last = time.time()def on_close(self):'''Channel is closed'''print("connection is closed")self.loop.stop()def check_origin(self, origin):return Truedef initiate_server():#create a tornado application and provide the urlsapp = tornado.web.Application(web_socket_handler.route_urls())#setup the serverserver = tornado.httpserver.HTTPServer(app)server.listen(options.port)#start io/event looptornado.ioloop.IOLoop.instance().start()if __name__ == '__main__':initiate_server()

The above code will start the server on localhost and port as 4041.

上面的代碼將在localhost和端口4041上啟動服務器。

Connect to the server using a websocket client code (example below),

使用websocket客戶端代碼連接到服務器(以下示例),

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 (Client side):

輸出(客戶端):

>>Sending 'Hello, Server'... >>Sent >>Receiving... >>Received 'You are connected'

Output (Server side):

輸出(服務器端):

>>New client connected >>received message Hello, Server >>connection is closed

References:

參考文獻:

  • Tornado

    龍卷風

  • WebSocket

    WebSocket

翻譯自: https://www.includehelp.com/python/how-to-implement-a-websocket-server-using-tornado.aspx

總結

以上是生活随笔為你收集整理的如何使用Tornado实现WebSocket服务器?的全部內容,希望文章能夠幫你解決所遇到的問題。

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