twisted简介之reactor

Twisted是用Python实现的基于事件驱动的网络引擎框架,Twisted支持许多常见的传输及应用层协议,包括TCP、UDP、SSL/TLS、HTTP、IMAP、SSH、IRC以及FTP。就像Python一样,Twisted也具有“内置电池”(batteries-included)的特点。Twisted对于其支持的所有协议都带有客户端和服务器实现,同时附带有基于命令行的工具,使得配置和部署产品级的Twisted应用变得非常方便。

'''功能:从twisted.internet模块导入reactor
        示例启动reactor:reactor.run()   启动反应器
        此时程序会一直运行等待直到被强制终止
        这个现象不同于while循环,这里不占有CPU资源
'''

from twisted.internet import reactor

print('开始运行Running the reactor。。。')

reactor.run()

print('结束运行reactor。。。')

from twisted.internet import reactor
import time


def printTime():
    print('Current time is ', time.strftime('%H:%M:%S'))

def stopReactor():
    print('Stopping reactor...')
    reactor.stop()  # 终止reactor

for i in range(5):
    if i == 4 :
        reactor.callLater(i+1, stopReactor) # 启动到第五秒时调用终止reactor
    else:
        reactor.callLater(i+1, printTime)

print('开始运行Running the reactor。。。')
reactor.run()

print('结束运行reactor。。。')

—》开始运行Running the reactor。。。
Current time is 14:38:05
Current time is 14:38:06
Current time is 14:38:07
Current time is 14:38:08
Stopping reactor…
结束运行reactor。。。
[Finished in 5.5s]

'''功能:从twisted.internet模块导入reactor
        示例对比观看callLater的顺序
        示例终止reactor:reactor.stop()   终止反应器
        此时程序会一直运行到reactor.stop()被调用
        其中,reactor.callLater(等待的秒数,调用的函数) 是用来未来定时调用某函数的。
        可以看到,callLater可以进行参数回传调用
'''

from twisted.internet import reactor
import time


def printTime(x=0):
    print(x, 'Current time is ', time.strftime('%H:%M:%S'))

def stopReactor():
    print('Stopping reactor...')
    reactor.stop()  # 终止reactor

for i in range(5):
    if i == 0 :
        reactor.callLater(3, stopReactor) # 启动到第3秒时调用终止reactor,但是已经调用的函数则会执行完毕
    else:
        reactor.callLater(5-i, printTime, x=(5-i))

print('开始运行Running the reactor。。。')
reactor.run()

print('结束运行reactor。。。')

Reactor模式
Twisted实现了设计模式中的反应堆(reactor)模式,这种模式在单线程环境中调度多个事件源产生的事件到它们各自的事件处理例程中去。

Twisted的核心就是reactor事件循环。Reactor可以感知网络、文件系统以及定时器事件。它等待然后处理这些事件,从特定于平台的行为中抽象出来,并提供统一的接口,使得在网络协议栈的任何位置对事件做出响应都变得简单。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值