Hi,
I am trying to write a simple client program. It will connect to other "terminal/server" with ip address known ahead of time at some port (8889). Then it will listen to the port connected. I have written this code, but it will not work (crash). Basically, I have written the code to connect to other terminal first. Once it is connected, then I call "listenTCP" to listen to the port until it get "quit". (This is a modify version of the twisted code I have found from other sources, but I think it should work). The program would terminate by itself after a few seconds (3-4s). Can someone tell me what is wrong with the code? Thanks in advance.
from twisted.internet import reactor, defer, protocol
from twisted.protocols import basic
class CallbackAndDisconnectProto
col(protoc
ol.Protoco
l):
def connectionMade(self):
self.factory.deferred.call
back("Conn
ected!")
class ConnectionTestFactory(prot
ocol.Clien
tFactory):
protocol = CallbackAndDisconnectProto
col
def __init__(self):
self.deferred = defer.Deferred( )
def clientConnectionFailed(sel
f, connector, reason):
self.deferred.errback(reas
on)
class EchoProtocol(basic.LineRec
eiver):
def lineReceived(self, line):
if line == 'quit':
self.sendLine("Goodbye.")
self.transport.loseConnect
ion( )
else:
self.sendLine("You said: " + line)
reactor.stop()
class EchoServerFactory(protocol
.ServerFac
tory):
print "listening..."
protocol = EchoProtocol
def testConnect(host, port):
testFactory = ConnectionTestFactory( )
reactor.connectTCP(host, port, testFactory)
return testFactory.deferred
def handleSuccess(result, port):
print "Connected to port %i" % port
reactor.listenTCP(port,Ech
oServerFac
tory())
def handleFailure(failure, port):
print "Error connecting to port %i: %s" % (
port, failure.getErrorMessage( ))
reactor.stop( )
if __name__ == "__main__":
import sys
host = '192.168.0.2'
port = 8889
print "Connecting to ", host, " at port " , port
connecting = testConnect(host, port)
connecting.addCallback(han
dleSuccess
, port)
connecting.addErrback(hand
leFailure,
port)
reactor.run( )
Start Free Trial