[Twisted-Python] how to write an interactive client?

theshz theshz at gmail.com
Fri May 20 19:04:50 EDT 2005


Hi, I've written a simple twisted server, which accepts client connections,
and respond with some simple text depending on what the client sends. This
is working fine if I use telnet to connect to the server, and enter the
commands one at a time. I'd like to write a twisted client to simulate this,
i.e., the client has a list of commands to send, it will send one at a time,
(may be wait a little bit between the commands,) and print out the responses
from the server. I couldn't seem to get beyond the first command, following
code seems to send all the commands at the end, rather than one at a time,
how can I add sleep in between? Thanks:

from twisted.internet.protocol import ReconnectingClientFactory
from twisted.protocols import basic
from twisted.internet import reactor
from sys import stdout
import time

class MyClientProtocol(basic.LineReceiver):
 def lineReceived(self,data):
  stdout.write("Server:" + data+"\n"),

 def connectionMade(self):
      stdout.write("connectionMade\n")
      self.transport.write("start:\r\n")
      self.transport.write("command1:\r\n")
      self.transport.write("command2:\r\n")
      self.transport.write("command3:\r\n")
      self.transport.write("end:\r\n")


class MyClientFactory(ReconnectingClientFactory):
 def startedConnecting(self, connector):
  stdout.write("Started to connect\n")

 def buildProtocol(self,addr):
  stdout.write("Connected\nResetting reconnection delay")
  self.resetDelay()
  return MyClientProtocol()

 def clientConnectionLost(self, connector, reason):
  stdout.write("Lost connection, reason:" + reason)
  ReconnectingClientFactory.clientConnectionList(self, connector, reason)

 def clientConnectionFailed(self, connector,reason):
  stdout.write("Connection failed, reason:" + reason)
  ReconnectingClientFactory.clientConnectionFailed(self, connector, reason)

def main():
 reactor.connectTCP("localhost",82828, MyClientFactory())
 reactor.run()

if __name__ == '__main__':
 main()





More information about the Twisted-Python mailing list