from twisted.internet.task import react from twisted.internet.defer import Deferred from twisted.internet.protocol import Factory, connectionDone from twisted.internet.endpoints import TCP4ServerEndpoint from twisted.protocols.basic import LineReceiver class ChatProtocol(LineReceiver): def lineReceived(self, line): self.factory.send_message(self, line) def connectionMade(self): self.factory.connect(self) def connectionLost(self, reason=connectionDone): self.factory.disconnect(self) @property def address(self): return self.transport.getPeer() class ChatFactory(Factory, object): protocol = ChatProtocol def __init__(self): self.clients = [] def send_message(self, author, line): for protocol in self.clients: if protocol is not author: addr = protocol.address protocol.sendLine('{}:{}>>{}'.format(addr.host, addr.port, line)) def connect(self, protocol): self.clients.append(protocol) def disconnect(self, protocol): self.clients.remove(protocol) def main(reactor): endpoint = TCP4ServerEndpoint(reactor, 51234) endpoint.listen(ChatFactory()) return Deferred() if __name__ == '__main__': react(main)