wiki:Twistedの短いソースコード集

Version 2 (modified by nakiki, 13 years ago) (diff)

--

簡単な関数の実行

from twisted.internet import reactor

def printMsg():
  print 'test message'
  reactor.stop()

reactor.callLater(0, printMsg)
reactor.run()

TCPクライアント.接続だけ

class MyProtocol(protocol.Protocol):
  made = 0
  closed = 0

  def connectionMade(self):
    self.made = 1
    print self.transport.getPeer().host
    self.transport.loseConnection()

  def connectionLost(self, reason):
    self.closed = 1
    print 'connection lost'

class TCPClient(protocol.ClientFactory):
  def buildProtocol(self, addr):
    self.protocol = MyProtocol()
    return self.protocol

client = TCPClient()
reactor.connectTCP('www.accense.com', 80, client)
while not client.protocol or not client.protocol.closed:
  reactor.iterate()