• 初始twisted(一)


    1.与同步模型的优势:
    
        1.有大量的任务,一个时刻内至少有一个任务要运行
        2.任务执行大量的I/O,同步模型会因为任务阻塞而浪费大量时间
        3.任务之间相互独立,任务内部交互少.
    2.与同步模式客户端的差别:
    
        1.异步模式会一次性与全部服务器完成连接,而不是同步模式那样一次连接一个.
        2.用来通信的socket方法是非阻塞的,通过setblocking()实现.
        3.select模块中的select方法用来识别监视的socket是否有完成数据接收,如果没有,则阻塞.
        4.当从服务器读取数据时,会尽量多的从socket读取知道他阻塞为止,然后读下一个socket
    3.异步模式:
    
    异步模式客户端需要一个循环体来监视所有sokect,利用这个循环体来等待事件发生:reactor:
    
    wait for events----->handle events------>wait for events
    
    
    4.关于twisted基础编程的几点:
    
        1.twisted的reactor只有通过reactor.run()来启动
        2.reactor循环运行在主进程中.
        3.一旦启动,就会一直运行下去.
        4.reactor循环不消耗cpu
        5.reacotr不需要创建,引入即可.
    5.Hello world
    
        from twisted.internet import reactor
    
        def hello():
            print 'Hello world!'
            print 'Hello twisted!'
    
        reactor.callWhenRunning(hello) #hello 在reactor启动后被调用
        print 'Starting reactor!'
        reactor.run()
    6.第二个程序stop
    class CountDown(object): counter = 5 def count(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter,'............' self.counter -=1 reactor.callLater(1,self.count) #使用callLater注册一个回调函数,arg2为回调函数,arg1为在几秒后执行该回调函数. from twisted.internet import reactor reactor.callWhenRunning(CountDown().count) print 'Start!' reactor.run() print 'Stop!' Output: Start! 5...... 4...... 3...... 2...... 1...... Stop!

      

  • 相关阅读:
    第七周作业
    第六周作业
    第五周作业
    第四周作业
    第三周作业
    第二周作业
    求最大值及下标
    查找整数
    抓老鼠
    第五周作业
  • 原文地址:https://www.cnblogs.com/huangxiaohen/p/3855397.html
Copyright © 2020-2023  润新知