| 1 | from twisted.internet.protocol import Protocol, Factory |
|---|
| 2 | from twisted.protocols.basic import LineReceiver |
|---|
| 3 | from twisted.internet.protocol import ClientFactory |
|---|
| 4 | from twisted.internet import reactor |
|---|
| 5 | |
|---|
| 6 | import threading, time |
|---|
| 7 | |
|---|
| 8 | def log( st ): |
|---|
| 9 | print "%s %s" % (time.asctime(), st) |
|---|
| 10 | |
|---|
| 11 | # This is just about the simplest possible protocol |
|---|
| 12 | class Echo(Protocol): |
|---|
| 13 | def dataReceived(self, data): |
|---|
| 14 | """As soon as any data is received, write it back.""" |
|---|
| 15 | log( "echo %s" % data ) |
|---|
| 16 | self.transport.write(data) |
|---|
| 17 | |
|---|
| 18 | |
|---|
| 19 | class EchoClient(LineReceiver): |
|---|
| 20 | end="Bye-bye!" |
|---|
| 21 | def connectionMade(self): |
|---|
| 22 | log( "connectionMade" ) |
|---|
| 23 | self.sendLine("Hello, world!") |
|---|
| 24 | self.sendLine("What a fine day it is.") |
|---|
| 25 | self.sendLine(self.end) |
|---|
| 26 | |
|---|
| 27 | def lineReceived(self, line): |
|---|
| 28 | log( "receive: %s" % line ) |
|---|
| 29 | if line==self.end: |
|---|
| 30 | self.transport.loseConnection() |
|---|
| 31 | |
|---|
| 32 | class EchoClientFactory(ClientFactory): |
|---|
| 33 | protocol = EchoClient |
|---|
| 34 | |
|---|
| 35 | def clientConnectionFailed(self, connector, reason): |
|---|
| 36 | log( 'connection failed: %s' % reason.getErrorMessage() ) |
|---|
| 37 | reactor.stop() |
|---|
| 38 | |
|---|
| 39 | def clientConnectionLost(self, connector, reason): |
|---|
| 40 | log( 'connection lost: %s'% reason.getErrorMessage()) |
|---|
| 41 | reactor.stop() |
|---|
| 42 | |
|---|
| 43 | echo_client_factory = EchoClientFactory() |
|---|
| 44 | |
|---|
| 45 | def work_cherrypy(): |
|---|
| 46 | while True: |
|---|
| 47 | to = time.time() + 5 |
|---|
| 48 | while to > time.time(): |
|---|
| 49 | # sleep maybe interrupted |
|---|
| 50 | time.sleep( 1 ) |
|---|
| 51 | |
|---|
| 52 | #create tcp connection |
|---|
| 53 | df = reactor.connectTCP('localhost', 8000, echo_client_factory) |
|---|
| 54 | log( "connectTCP") |
|---|
| 55 | |
|---|
| 56 | def do_nothing(): |
|---|
| 57 | reactor.callLater( 30, do_nothing ) |
|---|
| 58 | |
|---|
| 59 | def main(): |
|---|
| 60 | # start echo server |
|---|
| 61 | f = Factory() |
|---|
| 62 | f.protocol = Echo |
|---|
| 63 | reactor.listenTCP(8000, f) |
|---|
| 64 | |
|---|
| 65 | # start worker thread - this is the source of cherrypy/turbogears requests |
|---|
| 66 | wthread = threading.Thread( target=work_cherrypy ) |
|---|
| 67 | wthread.setDaemon(True) |
|---|
| 68 | wthread.start() |
|---|
| 69 | |
|---|
| 70 | reactor.callLater( 30, do_nothing ) |
|---|
| 71 | reactor.run() |
|---|
| 72 | |
|---|
| 73 | main() |
|---|