Add python-eventlet package to MOS 9.0 repository
[packages/trusty/python-eventlet.git] / examples / twisted / twisted_server.py
1 """Simple chat demo application.
2 Listen on port 8007 and re-send all the data received to other participants.
3
4 Demonstrates how to
5  * plug in eventlet into a twisted application (join_reactor)
6  * how to use SpawnFactory to start a new greenlet for each new request.
7 """
8 from eventlet.twistedutil import join_reactor
9 from eventlet.twistedutil.protocol import SpawnFactory
10 from eventlet.twistedutil.protocols.basic import LineOnlyReceiverTransport
11
12 class Chat:
13
14     def __init__(self):
15         self.participants = []
16
17     def handler(self, conn):
18         peer = conn.getPeer()
19         print('new connection from %s' % (peer, ))
20         conn.write("Welcome! There're %s participants already\n" % (len(self.participants)))
21         self.participants.append(conn)
22         try:
23             for line in conn:
24                 if line:
25                     print('received from %s: %s' % (peer, line))
26                     for buddy in self.participants:
27                         if buddy is not conn:
28                             buddy.sendline('from %s: %s' % (peer, line))
29         except Exception as ex:
30             print(peer, ex)
31         else:
32             print(peer, 'connection done')
33         finally:
34             conn.loseConnection()
35             self.participants.remove(conn)
36
37 print(__doc__)
38 chat = Chat()
39 from twisted.internet import reactor
40 reactor.listenTCP(8007, SpawnFactory(chat.handler, LineOnlyReceiverTransport))
41 reactor.run()
42