python twisted框架_Python Twisted

Twsited异步网络框架

Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如:网络协议、线程、数据库管理、网络操作、电子邮件等。

事件驱动

简而言之,事件驱动分为二个部分:第一,注册事件;第二,触发事件。

例:程序一#!/usr/bin/env python

# -*- coding:utf-8 -*-

# event_drive.pyevent_list = []defrun():forevent inevent_list:obj =event()obj.execute()classBaseHandler(object):"""用户必须继承该类,从而规范所有类的方法(类似于接口的功能)"""defexecute(self):raiseException(‘you must overwrite execute‘)

程序二,动用程序一#!/usr/bin/env python

# -*- coding:utf-8 -*-fromsource importevent_drive

classMyHandler(event_drive.BaseHandler):defexecute(self):print‘event-drive execute MyHandler‘event_drive.event_list.append(MyHandler)event_drive.run()

Protocols

Protocols描述了如何以异步的方式处理网络中的事件。HTTP、DNS以及IMAP是应用层协议中的例子。Protocols实现了IProtocol接口,它包含如下的方法:makeConnection               在transport对象和服务器之间建立一条连接

connectionMade               连接建立起来后调用

dataReceived                 接收数据时调用

connectionLost               关闭连接时调用

Transports

Transports代表网络中两个通信结点之间的连接。Transports负责描述连接的细节,比如连接是面向流式的还是面向数据报的,流控以及可靠性。TCP、UDP和Unix套接字可作为transports的例子。它们被设计为“满足最小功能单元,同时具有最大程度的可复用性”,而且从协议实现中分离出来,这让许多协议可以采用相同类型的传输。Transports实现了ITransports接口,它包含如下的方法:write                   以非阻塞的方式按顺序依次将数据写到物理连接上

writeSequence           将一个字符串列表写到物理连接上

loseConnection          将所有挂起的数据写入,然后关闭连接

getPeer                 取得连接中对端的地址信息

getHost                 取得连接中本端的地址信息

将transports从协议中分离出来也使得对这两个层次的测试变得更加简单。可以通过简单地写入一个字符串来模拟传输,用这种方式来检查。

例:EchoServer

fromtwisted.internet importprotocol

fromtwisted.internet importreactor

classEcho(protocol.Protocol):defdataReceived(self, data):#只要twisted已收到数据就会把数据返回self.transport.write(data)defmain():factory =protocol.ServerFactory()factory.protocol =Echo

reactor.listenTCP(1234,factory)reactor.run()if__name__ ==‘__main__‘:main()

EchoClientfromtwisted.internet importreactor, protocol

classEchoClient(protocol.Protocol):"""Once connected, send a message, then print the result."""defconnectionMade(self):#只要建立连接成功就会执行此方法self.transport.write("hello alex!")defdataReceived(self, data):#只要收到数据就会调用此方法"As soon as any data is received, write it back."print("Server said:", data)self.transport.loseConnection()#如果数据未传完则等数据传输完毕后再调用此方法connectionLostdefconnectionLost(self, reason):print("connection lost")classEchoFactory(protocol.ClientFactory):protocol =EchoClient

defclientConnectionFailed(self, connector, reason):#如果连接不上就会调用此方法print("Connection failed - goodbye!")reactor.stop()#连接失败则关闭defclientConnectionLost(self, connector, reason):#如果连接过程中断开则执行此方法print("Connection lost - goodbye!")reactor.stop()#连接中断关闭# this connects the protocol to a server running on port 8000defmain():f =EchoFactory()reactor.connectTCP("localhost", 1234, f)reactor.run()# this only runs if the module was *not* importedif__name__ ==‘__main__‘:main()

运行服务器端脚本将启动一个TCP服务器,监听端口1234上的连接。服务器采用的是Echo协议,数据经TCP transport对象写出。运行客户端脚本将对服务器发起一个TCP连接,回显服务器端的回应然后终止连接并停止reactor事件循环。这里的Factory用来对连接的双方生成protocol对象实例。两端的通信是异步的,connectTCP负责注册回调函数到reactor事件循环中,当socket上有数据可读时通知回调处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值