事件驱动
简而言之,事件驱动分为二个部分:第一,注册事件;第二,触发事件。自定义事件驱动框架,命名为:“弑君者”:
事件服务器端:
1 __author__ = 'lizheng' 2 # !/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 event_list = [] 5 6 def run(): 7 for event in event_list: 8 obj = event() 9 obj.execute()10 11 12 class BaseHandler(object):13 """14 用户必须继承该类,从而规范所有类的方法(类似于接口的功能)15 """16 def execute(self):17 raise Exception('you must overwrite execute')
事件客户端,注册和触发事件
1 __author__ = 'lizheng' 2 # !/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 from day10 import event_drive 5 6 7 class MyHandler(event_drive.BaseHandler): 8 9 def execute(self):10 print('MyHandler is executing!')11 12 event_drive.event_list.append(MyHandler)13 event_drive.run()
Twsited异步网络框架
Twisted是一个事件驱动的网络框架,其中包含了诸多功能,例如:网络协议、线程、数据库管理、网络操作、电子邮件等。
EchoServer
1 __author__ = 'lizheng' 2 # !/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 from twisted.internet import protocol 5 from twisted.internet import reactor 6 #定义Echo类,相当于socketserver里的MyTCPHandler,继承protocal.Protocal 7 class Echo(protocol.Protocol): 8 def dataReceived(self, data): 9 self.transport.write(data)10 #定义主函数,将自己定的处理类Echo传给factory.protocol11 def main():12 factory = protocol.ServerFactory()13 factory.protocol = Echo14 #监听在factory,1234端口15 reactor.listenTCP(1234,factory)16 reactor.run()17 18 if __name__ == '__main__':19 main()
EchoClient
1 __author__ = 'lizheng' 2 # !/usr/bin/env python 3 #-*- coding:utf-8 -*- 4 from twisted.internet import reactor, protocol 5 6 #定义一个客户端协议类,继承protocol.Protocol 7 class EchoClient(protocol.Protocol): 8 #一旦连接,发送消息 9 def connectionMade(self):10 self.transport.write(bytes("hello alex!",'utf-8'))11 #收到消息,打印消息12 def dataReceived(self, data):13 print("Server said:", data)14 #打印完消息,调用connectionLost关闭连接15 self.transport.loseConnection()16 #关闭连接17 def connectionLost(self, reason):18 print("connection lost")19 #定义客户端工厂类20 class EchoFactory(protocol.ClientFactory):21 #将EchoClient传给protocol22 protocol = EchoClient23 #连接失败处理24 def clientConnectionFailed(self, connector, reason):25 print("Connection failed - goodbye!")26 reactor.stop()27 #连接丢失处理28 def clientConnectionLost(self, connector, reason):29 print("Connection lost - goodbye!")30 reactor.stop()31 32 33 34 def main():35 #客户端工厂实例化36 f = EchoFactory()37 #绑定本机的1234端口连接上服务端,传入客户端工厂实例进行消息发送和处理38 reactor.connectTCP("localhost", 1234, f)39 reactor.run()40 41 #程序主体42 if __name__ == '__main__':43 main()