[Twisted-Python] echo server using deferToThread
snacktime
snacktime at gmail.com
Sun Feb 6 20:15:34 MST 2005
I can't figure out why LineReceived never gets called in the client. Any ideas?
---------------------------------------------------------------------
Client Code:
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys
class EchoClient(LineReceiver):
end="GoodBye"
def connectionMade(self):
self.sendLine("Hello, world!")
def lineReceived(self, line):
print "receive:", line
if line==self.end:
self.transport.loseConnection()
class EchoClientFactory(ClientFactory):
protocol = EchoClient
def clientConnectionFailed(self, connector, reason):
print 'connection failed:', reason.getErrorMessage()
reactor.stop()
def clientConnectionLost(self, connector, reason):
print 'connection lost:', reason.getErrorMessage()
reactor.stop()
def main():
factory = EchoClientFactory()
reactor.connectTCP('localhost', 8000, factory)
reactor.run()
if __name__ == '__main__':
main()
--------------------------------------------------------------------------------
Server Code:
from twisted.internet.protocol import Protocol, Factory
from twisted.internet import defer, reactor
from twisted.python import threadable
from twisted.internet import threads
threadable.init(1)
import time
class GetData:
def Do(self):
time.sleep(3)
return 'Done'
### Protocol Implementation
# This is just about the simplest possible protocol
class Echo(Protocol):
def dataReceived(self, data):
reactor.callLater(0, self.RunThread, data)
def PrintData(self,data):
self.transport.write('GoodBye')
print "Sent GoodBye"
self.transport.loseConnection()
# Call reactor.stop() for testing so I don't have to kill -9 the server
reactor.stop()
def RunThread(self,data):
c = GetData()
d = threads.deferToThread(c.Do)
d.addCallback(self.PrintData)
def main():
f = Factory()
f.protocol = Echo
reactor.listenTCP(8000, f)
reactor.run()
if __name__ == '__main__':
main()
More information about the Twisted-Python
mailing list