分类: LINUX
2010-04-23 18:50:54
当然twisted是网络相关的操作,所以建立连接是这类程序的第一步,看看下面的例子吧:
from twisted.internet import reactor, protocol
#自己定义的协议,当factory建立连接后,剩下的事情就交个它处理了。
class QuickDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
print "Connected to %s." % self.transport.getPeer( ).host
self.transport.loseConnection( )
#它的作用是管理连接
class BasicClientFactory(protocol.ClientFactory):
protocol = QuickDisconnectProtocol
def clientConnectionLost(self, connector, reason):
print "Lost connection: %s" % reason.getErrorMessage( )
reactor.stop( )
def clientConnectionFailed(self, connector, reason):
print "Connection failed: %s" % reason.getErrorMessage( )
reactor.stop( )
reactor.connectTCP('', 80, BasicClientFactory( ))
reactor.run( )