Chat Server

A chat server is a more advanced application of the concepts covered in creating an asyncio echo server. It manages multiple chat clients, allowing them to send and receive messages. The server listens for client connections, handles user authentication, and broadcasts messages to all connected clients. It uses asyncio to manage asynchronous communication, maintaining a dictionary of connected clients and their stream writers. Additionally, it disconnects idle users after a minute of inactivity.

Connecting to the Chat Server

To connect to a chat server using Telnet, you can use the following command on the command line:

telnet localhost 8000

This command establishes a TCP connection to the server on the specified host and port.

Creating a Chat Server

While the chapter does not explicitly cover creating a chat server, it builds on the echo server example to create a chat server and chat client. Below is a listing of a chat server implementation using asyncio.

[Listing 8.13 A Chat Server](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-8/117)

import asyncio
import logging
from asyncio import StreamReader, StreamWriter
 
 
class ChatServer:
 
    def __init__(self):
        self._username_to_writer = {}
 
    async def start_chat_server(self, host: str, port: int):
        server = await asyncio.start_server(self.client_connected, host, port)
 
        async with server:
            await server.serve_forever()
 
    async def client_connected(self, reader: StreamReader, writer: StreamWriter):#1
        command = await reader.readline()
        print(f'CONNECTED {reader} {writer}')
        command, args = command.split(b' ')
        if command == b'CONNECT':
            username = args.replace(b'\n', b'').decode()
            self._add_user(username, reader, writer)
            await self._on_connect(username, writer)
        else:
            logging.error('Got invalid command from client, disconnecting.')
            writer.close()
            await writer.wait_closed()
 
    def _add_user(self, username: str, reader:                                   #2
     StreamReader, writer: StreamWriter):                                        #2
        self._username_to_writer[username] = writer
        asyncio.create_task(self._listen_for_messages(username, reader))
 
    async def _on_connect(self, username: str, writer: StreamWriter):            #3
        writer.write(f'Welcome! {len(self._username_to_writer)} user(s) are online!\n'.encode())
        await writer.drain()
        await self._notify_all(f'{username} connected!\n')
 
    async def _remove_user(self, username: str):
        writer = self._username_to_writer[username]
        del self._username_to_writer[username]
        try:
            writer.close()
            await writer.wait_closed()
        except Exception as e:
            logging.exception('Error closing client writer, ignoring.', exc_info=e)
 
    async def _listen_for_messages(self,
                                   username: str,
                                   reader: StreamReader):                        #4
        try:
            while (data := await asyncio.wait_for(reader.readline(), 60)) != b'':
                await self._notify_all(f'{username}: {data.decode()}')
            await self._notify_all(f'{username} has left the chat\n')
        except Exception as e:
            logging.exception('Error reading from client.', exc_info=e)
            await self._remove_user(username)
 
    async def _notify_all(self, message: str):                                   #5
        inactive_users = []
        for username, writer in self._username_to_writer.items():
            try:
                writer.write(message.encode())
                await writer.drain()
            except ConnectionError as e:
                logging.exception('Could not write to client.', exc_info=e)
                inactive_users.append(username)
 
        [await self._remove_user(username) for username in inactive_users]
 
 
async def main():
    chat_server = ChatServer()
    await chat_server.start_chat_server('127.0.0.1', 8000)
 
 
asyncio.run(main())
#1 Wait for the client to provide a valid username command; otherwise, disconnect them.
#2 Store a user’s stream writer instance and create a task to listen for messages.
#3 Once a user connects, notify all others that they have connected.
#4 Listen for messages from a client and send them to all other clients, waiting a maximum of a minute for a message.
#5 Send a message to all connected clients, removing any disconnected users.

This code demonstrates how to implement a basic chat server using Python's asyncio library. The server handles client connections, manages user authentication, and broadcasts messages to all connected clients. It also includes error handling and user disconnection logic.

FAQ (Frequently asked questions)

What does the Telnet command do when connecting to a chat server?

How does a chat server handle user authentication?

What happens to idle users on a chat server?

How does the chat server notify users of new connections?

What happens if a client sends an invalid command to the chat server?

What does the chat server do with disconnected users?