什么是龙卷风? (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

如何使用Tornado实现WebSocket服务器?相关推荐

  1. python tornado websocket_Python Tornado实现WEB服务器Socket服务器共存并实现交互的方法...

    1.背景 最近有个项目,需要搭建一个socket服务器,一个web服务器,然后实现两个服务器之间的通讯交互.刚开始的方案是用Python中socket模块实现一个多线程的socket服务器,然后用Fl ...

  2. python web 服务器实时监控 websocket_python实现websocket服务器,可以在web实时显示远程服务器日志...

    一.开始的话 使用python简单的实现websocket服务器,可以在浏览器上实时显示远程服务器的日志信息. 之前做了一个web版的发布系统,但没实现在线看日志,每次发布版本后,都需要登录到服务器上 ...

  3. python websocket异步高并发_Python3.5异步和多个websocket服务器

    我在Ubuntu上使用pythonwebsockets4.0.1.我想有2个websocket服务器运行.我可以通过为每个线程创建2个线程和独立的事件循环来实现这一点.我所说的"某种工作&q ...

  4. js websocket同步等待_WebSocket硬核入门:200行代码,教你徒手撸一个WebSocket服务器...

    本文原题"Node.js - 200 多行代码实现 Websocket 协议",为了提升内容品质,有较大修订. 1.引言 最近正在研究 WebSocket 相关的知识,想着如何能自 ...

  5. 在IIS上搭建WebSocket服务器(三)

    在IIS上搭建WebSocket服务器(三) 原文:在IIS上搭建WebSocket服务器(三) 编写客户端代码 1.新建一个*.html文件. ws = new WebSocket('ws://19 ...

  6. websocket 更新点位 浏览器卡顿_我们来看看Swoole是如何实现WebSocket服务器及客户端的...

    php自学中心 2019-11-08 10:25:30 文章来自:laravel学院WebSocket 概述 在此之前,有必要对 WebSocket 的原理做简单的说明,WebSocket 复用了 H ...

  7. 基于Boost::beast模块的异步WebSocket服务器

    Boost:基于Boost::beast模块的异步WebSocket服务器 实现功能 C++实现代码 实现功能 基于Boost::beast模块的异步WebSocket服务器 C++实现代码 #inc ...

  8. 基于Boost::beast模块的协程WebSocket 服务器

    Boost:基于Boost::beast模块的协程WebSocket 服务器 实现功能 C++实现代码 实现功能 基于Boost::beast模块的协程WebSocket 服务器 C++实现代码 #i ...

  9. 基于Boost::beast模块的快速WebSocket服务器

    Boost:基于Boost::beast模块的快速WebSocket服务器 实现功能 C++实现代码 实现功能 基于Boost::beast模块的快速WebSocket服务器 C++实现代码 #inc ...

最新文章

  1. 什么是ownership?
  2. C#种死锁:事务(进程 ID 112)与另一个进程被死锁在 锁
  3. 30、驱动程序调用驱动程序
  4. 自定义ClassLoader和双亲委派机制
  5. sublime设置自己的快捷键
  6. MongoDB集群——副本集
  7. python大众点评最新字体加密破解完结
  8. Java基础篇:如何嵌套try语句?
  9. 毕设:基于Spring Boot的旅游攻略网的设计与实现
  10. 记一次优化天猫商城系统高并发的经验
  11. 初学C语言 输出图形
  12. IDEA怎么换背景颜色
  13. 工厂食堂3D指纹考勤系统解决方案
  14. 转载: 找不到MSVCR90.dll、Debug vs Release及cppLapack相关
  15. 配置安装最新的Vue脚手架
  16. 介绍一种AI的抠图方法
  17. lempel ziv算法c语言,数学之路-python计算实战(4)-Lempel-Ziv压缩(2)(示例代码)
  18. 人工智能原理、算法和实践思维导图
  19. css【详解】grid布局—— 网格布局(栅格布局)
  20. java中404什么意思_java web中关于404问题的根本来源与解决

热门文章

  1. java jdbc rowset_JAVA基础知识之JDBC——RowSet
  2. xp系统如何开启共享服务器,xp系统怎么关闭共享服务 xp系统共享打印机如何设置...
  3. word把选择答案弄到题目里_老师们看过来,如何快速整理试题答案
  4. c++用牛顿法开多次根_望远镜的历史之三:大神出世,改变望远镜历史的竟然是牛顿...
  5. 虚拟跳线软件干什么用的_疯狂刷单!用违法软件生成虚拟手机号,“骑手”半年“刷单”牟利60余万,百米内竟有万笔订单 | 申晨间...
  6. 计算机技术博客博客知乎,我的技术博客的选择:CSDN、博客园、简书、知乎专栏仍是Github Page?...
  7. strocli64 源码_storcli 简易使用介绍
  8. ActiveMQ学习总结(3)——spring整合ActiveMQ
  9. [js高手之路] html5 canvas系列教程 - 掌握画直线图形的常用API
  10. 嵌入式linux面试题解析(四)——逻辑推理一