| 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 |
class MyChat(basic.LineReceiver): |
| 11 |
def connectionMade(self): |
| 12 |
print("Got new client!") |
| 13 |
self.factory.clients.append(self) |
| 14 |
|
| 15 |
def connectionLost(self, reason): |
| 16 |
print("Lost a client!") |
| 17 |
self.factory.clients.remove(self) |
| 18 |
|
| 19 |
def lineReceived(self, line): |
| 20 |
print("received", repr(line)) |
| 21 |
for c in self.factory.clients: |
| 22 |
c.message(line) |
| 23 |
|
| 24 |
def message(self, message): |
| 25 |
self.transport.write(message + b"\n") |
| 26 |
|
| 27 |
|
| 28 |
from twisted.application import internet, service |
| 29 |
from twisted.internet import protocol |
| 30 |
|
| 31 |
factory = protocol.ServerFactory() |
| 32 |
factory.protocol = MyChat |
| 33 |
factory.clients = [] |
| 34 |
|
| 35 |
application = service.Application("chatserver") |
| 36 |
internet.TCPServer(1025, factory).setServiceParent(application) |