Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >3..Twisted学习

3..Twisted学习

作者头像
py3study
发布于 2020-01-20 08:44:11
发布于 2020-01-20 08:44:11
53400
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行

写这个主要是为了自己理解Twisted的文档

建立一个finger服务

你不需要调用Twisted,Twisted会自己运行。reactor是Twisted的主循环,想python的其他主循环一样。每个Twisted只有一个reactor。一旦启动他就会不停的运行下去,响应一个又一个请求。

from twisted.internet import reactor返回当前的reactor。如果你不选择一个reactor的话,它会默认选择。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 
 3 class FingerProtocol(protocol.Protocol):
 4     pass
 5 
 6 class FingerFactory(protocol.ServerFactory):
 7     protocol = FingerProtocol
 8 
 9 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
10 fingerEndpoint.listen(FingerFactory())
11 reactor.run()

这个流程看过前两章的应该很熟悉了,先创建协议,再创建工厂,然后主循环。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 
 3 class FingerProtocol(protocol.Protocol):
 4     def connectionMade(self):
 5         self.transport.loseConnection()
 6 
 7 class FingerFactory(protocol.ServerFactory):
 8     protocol = FingerProtocol
 9 
10 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
11 fingerEndpoint.listen(FingerFactory())
12 reactor.run()

这个是增加了一个连接之后的初始化配置

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 from twisted.protocols import basic
 3 
 4 class FingerProtocol(basic.LineReceiver):
 5     def lineReceived(self, user):
 6         self.transport.loseConnection()
 7 
 8 class FingerFactory(protocol.ServerFactory):
 9     protocol = FingerProtocol
10 
11 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
12 fingerEndpoint.listen(FingerFactory())
13 reactor.run()

这个是按行读取数据,就是按照你的\r\n读取数据,之后关闭连接

写一个读取用户名,返回错误,断开连接的finger

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 from twisted.protocols import basic
 3 
 4 class FingerProtocol(basic.LineReceiver):
 5     def lineReceived(self, user):
 6         self.transport.write(b"No such user\r\n")
 7         self.transport.loseConnection()
 8 
 9 class FingerFactory(protocol.ServerFactory):
10     protocol = FingerProtocol
11 
12 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
13 fingerEndpoint.listen(FingerFactory())
14 reactor.run()

这个就是按行读取,返回一句话,之后关闭连接

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 from twisted.protocols import basic
 3 
 4 class FingerProtocol(basic.LineReceiver):
 5     def lineReceived(self, user):
 6         self.transport.write(self.factory.getUser(user)+ b"\r\n")
 7         self.transport.loseConnection()
 8 
 9 class FingerFactory(protocol.ServerFactory):
10     protocol = FingerProtocol
11 
12     def getUser(self, user):
13         return b"No such user"
14 
15 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
16 fingerEndpoint.listen(FingerFactory())
17 reactor.run()

增加获取用户名的函数

在协议之中调用工厂方法,可以用self.factory,这个就是指向工厂的,因为工厂类实际上是它的父类。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, endpoints
 2 from twisted.protocols import basic
 3 
 4 class FingerProtocol(basic.LineReceiver):
 5     def lineReceived(self, user):
 6         self.transport.write(self.factory.getUser(user) + b"\r\n")
 7         self.transport.loseConnection()
 8 
 9 class FingerFactory(protocol.ServerFactory):
10     protocol = FingerProtocol
11 
12     def __init__(self, users):
13         self.users = users
14 
15     def getUser(self, user):
16         return self.users.get(user, b"No such user")
17 
18 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
19 fingerEndpoint.listen(FingerFactory({ b'moshez' : b'Happy and well'}))
20 reactor.run()

初始化一个字典,如果你输入的用户名没有在字典里边,就会返回默认值。

Defereds

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.internet import protocol, reactor, defer, endpoints
 2 from twisted.protocols import basic
 3 
 4 class FingerProtocol(basic.LineReceiver):
 5     def lineReceived(self, user):
 6         d = self.factory.getUser(user)
 7 
 8         def onError(err):
 9             return 'Internal error in server'
10         d.addErrback(onError)
11 
12         def writeResponse(message):
13             self.transport.write(message + b'\r\n')
14             self.transport.loseConnection()
15         d.addCallback(writeResponse)
16 
17 class FingerFactory(protocol.ServerFactory):
18     protocol = FingerProtocol
19 
20     def __init__(self, users):
21         self.users = users
22 
23     def getUser(self, user):
24         return defer.succeed(self.users.get(user, b"No such user"))
25 
26 fingerEndpoint = endpoints.serverFromString(reactor, "tcp:1079")
27 fingerEndpoint.listen(FingerFactory({b'moshez': b'Happy and well'}))
28 reactor.run()

在这个里边,我么使用了defer,其实也就仅仅修改了getUser方法。Defereds循序由事件驱动程序,也就是说,如果程序中的一个任务正在等待数据,程序可以去执行其他操作,这叫做异步执行。

上边的代码测试了一下,是按照队列执行的,就是说两个客户端发送数据,如果第一个客户端设置延迟返回5秒,那么之后5秒后,第二个客户端才会被响应。

解释一下deferred:

大家可以去看

https://www.cnblogs.com/zhangjing0502/archive/2012/05/16/2504415.html  作者:很多不懂呀。。

Twisted

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
 1 from twisted.application import service, strports
 2 from twisted.internet import protocol, reactor, defer
 3 from twisted.protocols import basic
 4 
 5 class FingerProtocol(basic.LineReceiver):
 6     def lineReceived(self, user):
 7         d = self.factory.getUser(user)
 8 
 9         def onError(err):
10             return 'Internal error in server'
11         d.addErrback(onError)
12 
13         def writeResponse(message):
14             self.transport.write(message + b'\r\n')
15             self.transport.loseConnection()
16         d.addCallback(writeResponse)
17 
18 class FingerFactory(protocol.ServerFactory):
19     protocol = FingerProtocol
20 
21     def __init__(self, users):
22         self.users = users
23 
24     def getUser(self, user):
25         return defer.succeed(self.users.get(user, b"No such user"))
26 
27 application = service.Application('finger', uid=1, gid=1)
28 factory = FingerFactory({b'moshez': b'Happy and well'})
29 strports.service("tcp:79", factory, reactor=reactor).setServiceParent(
30     service.IServiceCollection(application))

可能你已经发现了,我们的协议类从上边开始就没变过,事实上,以后也很少会变了,主要是在工厂里更改。

这个例子是告诉twisted您的应用程序在哪里,使用的是application

from twisted.application import service,strports

在这里我们没有再使用serverFormString来设置地址端口,我们用了他的应用程序来启动,strports.service。注意,当它被实例化的时候,这个程序对象不会引用协议和工厂!

任何把application当做父对象的服务将会在twisted启动的时候被启动。总之,他就是来管理启动服务和关闭服务的。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/04/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python 网络框架twisted基础学习及详细讲解
twisted网络框架的三个基础模块:Protocol, ProtocolFactory, Transport.这三个模块是构成twisted服务器端与客户端程序的基本。 Protocol:Protocol对象实现协议内容,即通信的内容协议 ProtocolFactory: 是工厂模式的体现,在这里面生成协议 Transport: 是用来收发数据,服务器端与客户端的数据收发与处理都是基于这个模块 在windows中安装twisted需要先安装pywin32,自己去下载下就行。随后pip install twisted就会帮我们安装twisted以及zope。 我们结合一张图,以及一段程序来理解下twisted的基础实现:
Ryan_OVO
2023/10/18
8980
python 网络框架twisted基础学习及详细讲解
python中的twisted入门
Twisted是一个基于事件驱动的网络编程框架,专门用于构建可扩展、高性能和可靠的网络应用程序。它提供了丰富的网络协议和工具,可以实现客户端和服务器端的通信,支持TCP、UDP、SSL等协议。Twisted还具有异步编程的能力,能够处理大量并发连接而不会阻塞主程序。
大盘鸡拌面
2023/10/22
4430
再讲Python不能做游戏后端开发我揍你嗷!​ Twisted——基于事件驱动的Python网络框架
在大家知道阿巩做游戏后端开发后最常有的对话是:你转做C++了吗,我说是Python,然后对面意味深长的叹口气,哦~不过Python慢啊;性能不如静态语言;Python适合写写脚本巴拉巴拉……硬了,拳头硬了,于是就有了这个标题。
才浅Coding攻略
2022/12/12
1.3K0
再讲Python不能做游戏后端开发我揍你嗷!​ Twisted——基于事件驱动的Python网络框架
python——twisted
Twisted is an event-driven networking engine in Python. It was born in the early 2000s, when the writers of networked games had few scalable and no cross-platform libraries, in any language, at their disposal. The authors of Twisted tried to develop games in the existing networking landscape, struggled, saw a clear need for a scalable, event-driven, cross-platform networking framework and decided to make one happen, learning from the mistakes and hardships of past game and networked application writers.
py3study
2020/01/09
7120
python twisted deferredlist用法
from twisted.internet import reactor,defer,protocol
用户5760343
2022/05/14
2180
python twisted TCP通信 脚本
-------------------server-------------------
用户5760343
2022/05/14
6980
twisted高并发库transport函数处理数据包的些许问题
还是在学校时间比较多, 能够把时间更多的花在学习上, 尽管工作对人的提升更大, 但是总是没什么时间学习, 而且工作的气氛总是很紧凑, 忙碌, 少了些许激情吧。适应就好了.延续着之前对twisted高并
Ryan_OVO
2023/10/18
2370
twisted高并发库transport函数处理数据包的些许问题
开源蜜罐Opencanary的实践与扩展
具有一定规模的公司都会有自己的机房,当网络规模和硬件系统到达一定程度,就需要跟进各种安全预警防护手段,而蜜罐系统就是一种常见的防护手段之一,蜜罐主要是通过在网络环境当中,用虚拟各种真实服务的守护进程,去模拟各种常见的应用服务,比如http、mysql、FTP服务等。
糖果
2019/11/20
6.1K0
猫头虎分享:Python库 Twisted 的简介、安装、用法详解入门教程
今天猫头虎要和大家聊聊一个 Python 里非常强大、适合处理异步编程的库—— Twisted。很多粉丝都问过猫哥:如何在 Python 中处理复杂的异步网络请求?Twisted 就是答案之一。今天这篇文章会深入讲解它的安装、基本用法,并分享一些常见问题的解决方法。😉----
猫头虎
2024/10/17
5660
猫头虎分享:Python库 Twisted 的简介、安装、用法详解入门教程
Python Twisted
Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如:网络协议、线程、数据库管理、网络操作、电子邮件等。
py3study
2020/01/08
9200
python twisted 建立一个简单连接tcpConnection
from twisted.internet import reactor,protocol
用户5760343
2022/05/14
3210
如何使用Twisted Deferred周期性地调用
在 Twisted 中,Deferred 是一个用于处理异步操作结果的对象。当你想周期性地执行一个异步任务时,可以使用 LoopingCall,它结合了 Twisted 的事件循环来周期性地调用一个函数,并返回一个 Deferred 对象。
华科云商小徐
2025/02/05
660
python——客户端
twisted是一个设计非常灵活的框架,通过它可以写出功能强大的客户端,然而要在代码中使用非常多的层次结构。这个文档包括创建用于TCP,SSL和Unix sockets的客户端 在 底层,实际上完成协议语法和处理的是Protocol类。这个类通常是来自于twisted.internet.protocol.Protocol。大 多数的protocol handlers继承自这个类或它的子类。protocol类的一个实例将在你连接到服务器时被初始化,在断开连接时结束。这意味着持久的配置不会被保存 在Protocol中。 持久的配置将会保存在Factory类中,它通常继承自 twisted.internet.protocol.Factory(或者 twisted.internet.protocol.ClientFactory)。默认的factory类仅仅实例化Protocol,并且设置 factory属性指向自己。这使得Protocol可以访问、修改和持久配置。 Protocol 
py3study
2020/01/14
2.9K0
python twisted详解2
转载:作者:dave@http://krondo.com/slow-poetry-and-the-apocalypse/ 译者:杨晓伟(采用意译) from twisted.internet import reactor reactor.callWhenRunning(funcname) reactor.run()
用户5760343
2022/05/14
2860
python twisted diferred使用
Deferred 可以按照这种方式说明:可能你在饭店中遇到过这个问题,如果你在等待自己喜欢 的桌子时,在一旁哼哼小曲。带个寻呼机是个好主意,它可以让你在等待的时候不至于孤零 零的站在那里而感到无聊。你可以在这段时间出去走走,到隔壁买点东西。当桌子可用时, 寻呼机响了,这时你就可以回到饭店去你的位置了。 一个Deferred 类似于这个寻呼机。它提供了让程序查找非同步任务完成的一种方式,而在这 时还可以做其他事情。当函数返回一个Deferred 对象时,说明获得结果之前还需要一定时间。 为了在任务完成时获得结果,可以为Deferred 指定一个事件处理器。 1、Deferred.callback,,,,,,,Deferred.errorback 当调用一个可以返回Deferred 的函数时,使用Deferred.addCallback 方法指定返回结果时调 用的函数。使用Deferred.addErrback 方法指定执行发生异常时调用的函数。 2 from twisted.internet import reactor,defer,protocol
用户5760343
2022/05/14
2450
使用Twisted框架实现客户端和服务器之间的数据传输
使用 Twisted 框架来实现客户端和服务器之间的数据传输非常简单。Twisted 是一个异步事件驱动的框架,常用于构建网络应用程序。下面是一个简单的示例,展示了如何使用 Twisted 来实现客户端和服务器之间的基本数据传输。
华科云商小徐
2025/02/08
1220
使用python+django+twistd 开发自己的操作和维护系统的一个
许多开源操作系统和维护系统,例nagios、zabbix、cati等等,但是,当他们得到的时间自己的个性化操作和维护需求,始终无力!
全栈程序员站长
2022/07/05
4720
使用python+django+twistd 开发自己的操作和维护系统的一个
python 初次使用twisted
[root@centos python]# python twisted_check_tcp_port.py 127.0.0.1:80
py3study
2020/01/06
6500
python twisted 客户端服务端通信
from twisted.internet import reactor from twisted.internet.protocol import Protocol, Factory
用户5760343
2022/05/14
1K0
[PYTHON] 核心编程笔记(16.P
套接字只有两种一种是面向连接套接字,即在通讯之前一定要建立一条连接,这种通讯方式提供了顺序的,可靠的不会重复的数据传输,每一份要发送的信息都会拆分成多份,每份都会不多不少的到达目的地后重新按顺序拼装起来,传给正在等待的应用程序
py3study
2020/01/08
1.4K0
相关推荐
python 网络框架twisted基础学习及详细讲解
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验