Pub Sub is a system architecture where clients can Subscribe to channels/topics where other clients can Publish messages. The subscribers have no knowledge of the publishers nor the publishers of the subscribers. A central broker is responsible for managing subscriptions, receiving messages from publishers and pushing messages to subscribers. Brokers can also be clients themselves, forming a hub topology.
The broker must:
- accept multiple concurrent client connections
- hold client-channel subscriptions
- handle subscription messages
- handle publish messages
- receive messages from publishers and send to appropriate subscribers
When a client disconnects from the broker all of its subscriptions are lost. If it reconnects it must subscribe again. The client does not receive any messages that were sent on a channel before it subscribed.
See Protocol for details of the command and message format.
- Run
python3 broker.py
- Run
python3 client.py
- Verify that both work and the broker prints the message from the client.
- Modify
Broker.handle_client
to process the message based on thecommand
key of the message. - For now the broker can just write to the client socket with the appropriate message ( defined in the Protocol). Later we will implement the actual functionality for subscribe, unsubscribe, publish.
- Restart both broker and client and verify that the client prints the acknowledgement message after sending the
subscribe
command. - Implement higher level functions for
subscribe
,unsubscribe
andpublish
inclient.py
. subscribe(channel)
unsubscribe(channel)
publish(channel, message)
- Modify the client main to use these higher level functions.
- Implement a separate publisher script that creates a client object that publishes to one or more channels in a loop every second. This is useful for testing the client.
- Go back to
broker.py
and modify it to keep track of client channel subscriptions. Remember that socket objects are hashable so they can be used as keys in adict
and as elements of aset
. - Modify
Broker.handle_client
to correctly handle messages with thePUBLISH
command. The broker should iterate through all client sockets that are subscribed to the given channel and send aMESSAGE
message to them. - Run the broker, client and publisher and verify that the client receives all the messages it should, but none for other channels.
- Run multiple clients/publishers and see if things still work.
- Implement a 2 way chat script that listens on channels and publishes user input to some channels. Ideally it should use threads so the listening is not interrupted to send commands.
- Optimise the socket handling code to be more efficient.
- Measure how many simultaneous clients your broker can support. What are the limits? Why?