We will build a publish-subscribe paradigm based server-client system in this recipe. In this simple application, all the clients are subscribed to all the messages sent by the other clients. This can be configured further to alter the client or server behavior.
Listing 4.11 explains the code for a publish/subscribe server as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition -- Chapter - 3 # This program is optimized for Python 2.7.12 and Python 3.5.2. # It may run on any other version with/without modifications. import argparse from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic class PubProtocol(basic.LineReceiver): def __init__(self, factory): self.factory = factory def connectionMade(self): self.factory.clients.add(self) def connectionLost(self, reason): self.factory.clients.remove(self) def lineReceived(self, line): for c in self.factory.clients: source = u"<{}> ".format(self.transport.getHost()).encode("ascii") c.sendLine(source + line) class PubFactory(protocol.Factory): def __init__(self): self.clients = set() def buildProtocol(self, addr): return PubProtocol(self) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Socket Server
Example with Epoll') parser.add_argument('--port', action="store", dest="port",
type=int, required=True) given_args = parser.parse_args() port = given_args.port endpoints.serverFromString(reactor,
"tcp:%s" %port).listen(PubFactory()) reactor.run()
Run the following script to start the server in the specified port:
$ python 4_11_twisted_async_server.py --port=9999
Now, start two or more telnet clients to the same port. Type something from one of those telnet instances, and you will be able to see the same message echoed from all the client (telnet) instances:
Sending telnet client: $ telnet localhost 9999 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. zszz <IPv4Address(TCP, '127.0.0.1', 9999)> zszz Receiving telnet client: $ telnet localhost 9999 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. <IPv4Address(TCP, '127.0.0.1', 9999)> zszz
The following screenshot indicates the outputs of the environment: publish/subscribe server along with four telnet clients subscribed to the messages sent to the server by other instances: