Chat Server Example
This lesson walks the reader through the design and implementation of a toy chat-server.
We'll cover the following...
Chat Server
Problem
Let's embark on a more realist albeit toy-example of creating a server that enables instant messaging or chatting among various participants. You may consider this problem a dumbed-down version of full-blown real life chat room servers.
Solution
We can implement our chat server using either a multithreaded approach or a single-threaded asyncio-based approach. We'll explore and implement both the approaches and contrast them at the end.
Our chat server only allows three operations and receives them as commands.
register: A client can register with the server by sending a comma separated command string "register,<username>", where username is the name of the client intending to register.
list: A client can retrieve the list of other clients already registered on the server by sending the command string "list,friends". The client receives a comma-separated string of usernames including its own.
chat: A client can request a chat message be sent to a friend using the command string "chat,<username>", where username is an existing registered client on the server.
Important Note
The reader might find us making assumptions and taking shortcuts in the implementations we present. The reason is that our emphasis isn't on the networking aspects of the problem or its stability. Rather, the focus is on illuminating the differences between the two concurrency paradigms. We'll call out the simplifications and assumptions we make as we go along.
More generally, the implementations we present work for the happy paths we discuss. For example, we don't test for a client trying to erroneous input or attempting multiple register requests, etc. Also, the implementations run a simulation where the connected clients randomly chat with each other and we don't implement a graceful shutdown. We want the reader to be focused on the meat of the lesson here rather than be distracted by the niceties of a fully working solution.
Multithreaded Approach
In the multithreaded ...