~exarkun/+junk/training

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from twisted.internet import reactor
from twisted.internet.stdio import StandardIO
from twisted.internet.protocol import ServerFactory
from twisted.internet.ssl import DefaultOpenSSLContextFactory

from twisted.protocols.basic import LineOnlyReceiver

class Echoer(LineOnlyReceiver):
    delimiter = "\n"

    def lineReceived(self, line):
        self.factory.linecount += 1
        self.sendLine("%d: %s" % (self.factory.linecount, line))
        if self.factory.linecount > 3:
            port = self.factory.ports.pop()
            self.sendLine("Stopping %r" % (port,))
            port.stopListening()


class EchoFactory(ServerFactory):
    protocol = Echoer
    linecount = 0

    def doStart(self):
        print 'Starting', self


    def doStop(self):
        print 'Stopping', self


def main():
    factory = EchoFactory()

    factory.ports = []
    port = reactor.listenTCP(0, factory)
    print 'Listening on TCP port', port.getHost().port
    factory.ports.append(port)
    factory.ports.append(reactor.listenUNIX('echo', factory))
    factory.ports.append(reactor.listenSSL(
        12346,
        factory,
        DefaultOpenSSLContextFactory('server.key', 'server.pem')))

    echoer = Echoer()
    echoer.factory = factory
    StandardIO(echoer)

    reactor.run()
main()