Initial import to Tizen
[profile/ivi/python-twisted.git] / doc / core / examples / chatserver.py
1 """The most basic chat protocol possible.
2
3 run me with twistd -y chatserver.py, and then connect with multiple
4 telnet clients to port 1025
5 """
6
7 from twisted.protocols import basic
8
9
10
11 class MyChat(basic.LineReceiver):
12     def connectionMade(self):
13         print "Got new client!"
14         self.factory.clients.append(self)
15
16     def connectionLost(self, reason):
17         print "Lost a client!"
18         self.factory.clients.remove(self)
19
20     def lineReceived(self, line):
21         print "received", repr(line)
22         for c in self.factory.clients:
23             c.message(line)
24
25     def message(self, message):
26         self.transport.write(message + '\n')
27
28
29 from twisted.internet import protocol
30 from twisted.application import service, internet
31
32 factory = protocol.ServerFactory()
33 factory.protocol = MyChat
34 factory.clients = []
35
36 application = service.Application("chatserver")
37 internet.TCPServer(1025, factory).setServiceParent(application)