Ticket #3293: twisted_bug.py

File twisted_bug.py, 2.0 KB (added by LawrenceK, 6 years ago)

Shows issue I was trying to decsribe, more notes to be added

Line 
1from twisted.internet.protocol import Protocol, Factory
2from twisted.protocols.basic import LineReceiver
3from twisted.internet.protocol import ClientFactory
4from twisted.internet import reactor
5
6import threading, time
7
8def log( st ):
9    print "%s %s" % (time.asctime(), st) 
10
11# This is just about the simplest possible protocol
12class 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
19class 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
32class 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
43echo_client_factory = EchoClientFactory()
44
45def 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
56def do_nothing():
57    reactor.callLater( 30, do_nothing )
58
59def 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
73main()