如何使用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.mzph.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…