如何使用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: tornado
Running 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 tornado
libraries
'''
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket as ws
from tornado.options import define, options
import time
define('port', default=4041, help='port to listen on')
class web_socket_handler(ws.WebSocketHandler):
'''
This class handles the websocket channel
'''
@classmethod
def route_urls(cls):
return [(r'/',cls, {}),]
def simple_init(self):
self.last = time.time()
self.stop = False
def 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 True
def initiate_server():
#create a tornado application and provide the urls
app = tornado.web.Application(web_socket_handler.route_urls())
#setup the server
server = tornado.httpserver.HTTPServer(app)
server.listen(options.port)
#start io/event loop
tornado.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_connection
def 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/542909.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/542909.shtml
英文地址,請注明出處:http://en.pswp.cn/news/542909.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

電子增穩云臺_揭秘Dobby自拍無人機,電子增穩是黑科技?

揭秘Dobby自拍無人機,電子增穩是黑科技?2016年07月27日 10:47作者:廣州分站文章出處:泡泡網原創分享最近零度智控的Dobby自拍無人機橫空出世,主打「便攜」「自拍」兩大特色,一經眾籌便得到了大量的關注&…

拖動效果

css部分&#xff1a; <style type"text/css">.page{text-align:left;}.dragDiv{   border:1px solid #ddd;   padding:10px;   width:300px;   height:150px;   margin:0 auto;   border-radius:4px;    box-shadow:0 1px 2px #fefefe;    pos…

計算機組成比作人的什么位置,理學第章計算機組成上.ppt

理學第章計算機組成上.ppt第2章 計算機組成原理 2.1 計算機系統組成簡介 計算機系統由硬件和軟件兩大部分組成。若把一個計算機系統比作人的話&#xff0c;則硬件構成了計算機系統進行計算的軀干&#xff0c;軟件構成了計算機系統進行計算的大腦。 1 輸入部件 輸入部件用于向計…

Python | Tkinter中的文本區域和按鈕

Library: 圖書館&#xff1a; TkinterTkinter (Tkinter) Tkinter(Tk interface) is a Standard python library that is used to create easy, fast, and simple GUI applications. Tkinter(Tk接口)是一個標準的python庫&#xff0c;用于創建簡單&#xff0c;快速和簡單的GUI應…

python多行注釋以三個英文_Python中多行注釋可以包含在三對英文半角單引號('''''')或三對英文半角雙引號(\\\...

Python中多行注釋可以包含在三對英文半角單引號()或三對英文半角雙引號(\"\"\"\"\"\")之間答&#xff1a;√變化再現除了有形式結構的需要外,還暗示了()的變化:()答&#xff1a;表現內容治療與搶救休克首要的中心環節是答&#xff1a;積極去除病…

決心書之學習linux高級運維

我叫振鵬&#xff0c;我是一名在國企工作運維工程師&#xff0c;其實我不是一名合格運維工程師。為什么我選擇一條運維工程師的道路&#xff0c;當時候入門運維工程師比開發好玩&#xff0c;好入門&#xff0c;入門條件也不需要太苛刻&#xff0c;所以就選擇了一條運維工程師的…

淺談計算機程序設計語言,探討計算機程序設計語言教學

【文章摘要】隨著社會不斷的發展與進步&#xff0c;計算機作為現代先進產物的代表&#xff0c;已經很快的進入到社會中的各行各業。而程序設計作為計算機的核心內容&#xff0c;也同樣引起了大家的重視&#xff0c;同時計算機程序設計也是高校開設的一門重要學科&#xff0c;為…

十六進制轉八進制c++代碼_如何將十六進制代碼上傳到微控制器?

十六進制轉八進制c代碼Read: 8051 Microcontroller programming using Keil Uvision IDE 閱讀&#xff1a; 使用Keil Uvision IDE進行8051單片機編程 將HEX文件上傳到微控制器 (Uploading a HEX file to Microcontroller) Once you have developed the hex code for the progr…

win7驅動程序未經簽名可以使用嗎_手把手教你解決win7系統驅動程序簽名強制禁用的設置技巧...

win7系統穩定性好&#xff0c;使用者眾多&#xff1b;免不了會遇到win7系統驅動程序簽名強制禁用這樣的問題要處理&#xff0c;太多的用戶是不想看到win7系統驅動程序簽名強制禁用這種情況的&#xff0c;靠別人來解決問題太被動&#xff0c;只要我們自己找到win7系統驅動程序簽…

Linux下java環境及tomcat部署

1.下載JDK與Tomcat. jdk下載地址: http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html tomcat下載地址: http://tomcat.apache.org/download-70.cgi2.jdk安裝與配置. (1)jdk安裝 rpm包: # rpm -ivh jdk-7u55-linux-x6…

kotlin 查找id_Kotlin程序查找平行四邊形的區域

kotlin 查找idFormula to find area of Parallelogram: area base*height 查找平行四邊形面積的公式&#xff1a; area base * height Given the value of base and height, we have to find the area of Parallelogram. 給定基礎和高度的值&#xff0c;我們必須找到平行四邊…

計算機等級考試真題演示,全國計算機等級考試二級真題測試(答案)四、演示文稿題-日...

四、演示文稿題請在[答題]菜單下選擇[進入 ]命令&#xff0c;并按照題目要求完成下面的操作。注意&#xff1a;以下的文件必須都保存在考生文件夾下。某會計網校的劉老師正在準備有關《小企業會計準則》的培訓課件&#xff0c;她的助手已搜集并整理了一份該準則的相關資料存放在…

java工程師占比_Java工資怎么樣?哪個地方Java工作機會最多?

隨著IT產業的發展&#xff0c;JAVA語言因其獨有的特點&#xff0c;使其在各項服務器中應用程序的開發所占有一定的優勢&#xff0c;隨著JSP技術的發展&#xff0c;使Java語言的網絡應用更為實際化、更高效快捷&#xff0c;成為IT產業常用的技術。 越來越多的企業&#xff0c;因…

Nginx主配置文件nginx.conf中文詳解

第1章 nginx配置解釋圖解第2章 Nginx核心配置文件nginx.conf史上最細中文詳解2.1 定義Nginx運行的用戶和用戶組2.2 nginxworker進程數&#xff0c;即處理請求的進程&#xff08;熟稱負責接客的服務員&#xff09;2.3 cpu親和力配置&#xff0c;讓不同的進程使用不同的cpu2.4 全…

Windows中獲取和設置系統日期時間的C程序

In this C program, we have to set, get the system’s date and time. 在此C程序中&#xff0c;我們必須設置&#xff0c;獲取系統的日期和時間。 To get, set the system’s date and time, we need to include ‘dos.h’ header file. 要獲取&#xff0c;設置系統的日期和…

0到100速度測試軟件,【圖】到底如何完成 揭曉0-100公里/小時測試_汽車江湖

經常瀏覽汽車網站的朋友應該對0-100公里/小時加速測試并不會感到陌生&#xff0c;幾乎所有深度測試車型都會經歷的考驗&#xff0c;而在各個汽車官網上通常也會將這一數值標出。然而&#xff0c;這個成績到底是如何測出的&#xff0c;或許大多數人并不十分知曉&#xff0c;接下…

【hibernate merge】session1.merge(T entity)方法的含義和update方法的區別

注意&#xff1a; MERGE語句是SQL語句的一種。在SQL Server、Oracle數據庫中可用&#xff0c;MySQL、PostgreSQL中不可用。 1》session1.merge(T entity) 合并實體的方法。 2》merge的作用是&#xff1a;新new一個對象&#xff0c;如果該對象設置了ID&#xff0c;則這個對象就…

度量計算機外部傳輸單位,用來度量計算機外部設備傳輸率的是什么度量單位?...

用來度量計算機外部設備傳輸率的度量單位有&#xff1a;“MB/s”。MB是存儲容量&#xff0c;“MB/s”是傳輸速率&#xff0c;“MB/s”的含義是兆字節每秒&#xff0c;是指每秒傳輸的字節數量。基本概念bit(位&#xff0c;又名“比特”)&#xff1a;bit的縮寫是b&#xff0c;是計…

s7300plc串口通信_西門子S7-300/400串口通信模塊的信息與使用

原標題&#xff1a;西門子S7-300/400串口通信模塊的信息與使用1. 串行通訊模塊基本信息介紹CP340/CP341/CP440/CP441-1/CP441-2模塊是西門子S7-300/400系列PLC中的串行通訊模塊&#xff0c;這些模塊具有1個或2個(CP441-2)串行通訊接口(RS232C、20mA-TTY或RS485/422)。可以使用這…

Java LinkedList對象的clone()方法和示例

LinkedList對象clone()方法 (LinkedList Object clone() method) This method is available in package java.util.Collection and here, Collection is an interface. 該方法在java.util.Collection包中可用&#xff0c;在這里&#xff0c; Collection是一個接口。 This metho…