... continued
Explore how to implement a concurrent chat server in Python using the Async.io module. Understand the use of coroutines, event loops, and asynchronous callbacks to manage client connections without threading. Learn how to handle client messaging and server operations efficiently within a single-threaded asynchronous environment.
We'll cover the following...
The code widget below runs a simulation of the chat server with four users that message each other (including themselves) randomly.
Note that our implementation makes generous use of daemon threads so that when the main program thread exits, all the threads are killed and the code-widget doesn't time out. The output will show various users receiving hi messages from other users.
Next, we'll pivot our implementation to an asynchronous one.
Asynchronous Implementation
The asynchronous paradigm to implement a chat server involves using a single thread, usually called the event loop. In the case of Python, we'll not implement an event loop from scratch rather leverage asyncio module for the job.
Similar to the multithreaded approach, we need an entity to continuously listen for new incoming connections. We'll use the asyncio's start_server() coroutine. The coroutine takes in the server's hostname and a port to listen for incoming connections on. Once a client connects with the server, the coroutine invokes a user-specified callback to invoke. The callback includes the details to read and write from the connected client. The code snippet to start the server would look like as follows:
server_port = random.randint(10000, 65000)
server_host = "127.0.0.1"
chat_server = ChatServer(server_port)