Differences between revisions 1 and 2
Revision 1 as of 2005-12-01 01:17:25
Size: 2954
Editor: limodou
Comment:
Revision 2 as of 2005-12-01 01:17:56
Size: 2952
Editor: limodou
Comment:
Deletions are marked like this. Additions are marked like this.
Line 6: Line 6:
::-- limodou [[[DateTime(2005-12-01T01:17:25Z)]]] ::-- LawMe [[[DateTime(2005-12-01T01:17:25Z)]]]

开始TwistedStudyRecord写作 ::-- LawMe [DateTime(2005-12-01T01:17:25Z)] TableOfContents

开始Twisted学习写作

1. 啃嚼Twisted的初感(一)

啃嚼快一星期了,不再痛苦难受,逐渐尝出twisted的香甜美味、柔顺可口,开始适应twisted的套路。

twisted的套路,有哪些显著特点呢?接下去说说我品尝出的滋味。

前面把twisted的套路概括成一句话,“一个中心,两个基本点”,现在就从这个“中心”聊起。

Twisted 官方说,“ Twisted is an event-driven networking framework ”。事实的确如此。从其运行机制上看,event 是 Twisted 运转的引擎,是发生各种动作的启动器,是牵一发而动全身的核心部件。从其架构组成上看,它是紧密围绕event设计的;它的具体应用application,主要是定义、实现各式各样的event,由此完成不同网络协议的连接和输入输出任务,满足用户的实际需求;从其application的文本形式上,可以直接看到,它的应用程序,基本上由一系列event构成。

由此可见,说它以event为中心,符合实际情况。

Twisted 对event 的管理机制,可划分为后台和前台两种形式。

后台的管理,是Twisted 框架的内在机制,自动运行,对程序员透明无须干预,在程序文本中不见其踪迹。

前台的管理,是Twisted 授权程序员,在程序文本中显式写码来实现。程序员的工作,主要是按照既定的方式,实现 event。我们所关心、所用到的,是这部分东西(API)。

Twisted 众多的 event,分门别类、层次有序。前台管理中,有两个特别的 object,一个叫 reactor ,另一个叫defered。特别之处,在于它俩起着“事件管理器”的作用。下面,说说它俩。

1.1. 一、统领全局的 reactor

在 Twisted 应用中,reactor 的任务是为程序运行建立必须的全局循环(event loop),所起的作用,相当于 Python 应用中的 MainLoop()。

reactor 的用法很简单,一般只用两个:reactor.run() 启动全局循环,reactor.stop() 停止全局循环(程序终止)。

如果程序中没有调用reactor.stop() 的语句,程序将处于死循环,可以按键 Ctrl-C 强制退出。

下面是一个例子:

   1 from twisted.internet import reactor
   2 import time
   3 def printTime( ):
   4     print "Current time is", time.strftime("%H:%M:%S")
   5 
   6 def stopReactor( ):
   7     print "Stopping reactor"
   8     reactor.stop( )
   9 
  10 reactor.callLater(1, printTime) 
  11 #定时器,1秒钟后调用printTime()
  12 
  13 reactor.callLater(2, printTime)
  14 
  15 reactor.callLater(3, printTime)
  16 
  17 reactor.callLater(5, stopReactor)
  18 #定时器,5秒钟后调用stopReactor()
  19 
  20 print "Running the reactor..."
  21 
  22 reactor.run( )
  23 
  24 print "Reactor stopped."

LawMe/2005-12-01 (last edited 2009-12-25 07:09:50 by localhost)