Chat Client

The chat client is a crucial component of a chat application, designed to connect to a chat server, enabling users to send and receive messages in real-time. This client application is built using Python's asyncio library, which facilitates asynchronous communication with the server. The client prompts the user for a username, establishes a connection to the server, and listens for incoming messages. It also provides an input field for the user to send messages.

Overview

The chat client operates by creating asynchronous tasks to handle two main functions: listening for messages from the server and reading user input. This design ensures that the client can handle incoming messages and user inputs concurrently without blocking the main thread.

Implementation

Below is the implementation of the chat client, which demonstrates how to set up the client using asyncio:

[Listing 8.14 The Chat Client](https://livebook.manning.com/book/python-concurrency-with-asyncio/chapter-8/117)

import asyncio
import os
import logging
import tty
from asyncio import StreamReader, StreamWriter
from collections import deque
from chapter_08.listing_8_5 import create_stdin_reader
from chapter_08.listing_8_7 import *
from chapter_08.listing_8_8 import read_line
from chapter_08.listing_8_9 import MessageStore
 
 
async def send_message(message: str, writer: StreamWriter):
    writer.write((message + '\n').encode())
    await writer.drain()
 
 
async def listen_for_messages(reader: StreamReader,
                              message_store: MessageStore):                      #1
    while (message := await reader.readline()) != b'':
        await message_store.append(message.decode())
    await message_store.append('Server closed connection.')
 
 
async def read_and_send(stdin_reader: StreamReader,
                        writer: StreamWriter):                                   #2
    while True:
        message = await read_line(stdin_reader)
        await send_message(message, writer)
 
 
async def main():
    async def redraw_output(items: deque):
        save_cursor_position()
        move_to_top_of_screen()
        for item in items:
            delete_line()
            sys.stdout.write(item)
        restore_cursor_position()
 
    tty.setcbreak(0)
    os.system('clear')
    rows = move_to_bottom_of_screen()
 
    messages = MessageStore(redraw_output, rows - 1)
 
    stdin_reader = await create_stdin_reader()
    sys.stdout.write('Enter username: ')
    username = await read_line(stdin_reader)
 
    reader, writer = await asyncio.open_connection('127.0.0.1', 8000)            #3
 
    writer.write(f'CONNECT {username}\n'.encode())
    await writer.drain()
 
    message_listener = asyncio.create_task(listen_for_messages(reader, messages))#4
    input_listener = asyncio.create_task(read_and_send(stdin_reader, writer))
 
    try:
        await asyncio.wait([message_listener, input_listener], return_when=asyncio.FIRST_COMPLETED)
    except Exception as e:
        logging.exception(e)
        writer.close()
        await writer.wait_closed()
 
 
asyncio.run(main())

Key Components

  1. Listening for Messages: The listen_for_messages coroutine continuously reads messages from the server and appends them to a message store. If the server closes the connection, it appends a notification to the message store.

  2. Reading and Sending Messages: The read_and_send coroutine reads user input and sends it to the server. This allows users to communicate with others connected to the chat server.

  3. Connection Management: The client connects to the server using asyncio.open_connection, sending a CONNECT message with the username. It manages two tasks: one for listening to server messages and another for handling user input. The asyncio.wait function is used to wait for either task to complete, ensuring the client can handle disconnections or exceptions gracefully.

This chat client, when paired with a corresponding chat server, provides a simple yet effective way to facilitate real-time communication between users. The use of asyncio allows the client to handle multiple tasks concurrently, making it responsive and efficient.

FAQ (Frequently asked questions)

What technology does the chat client use for communication?

What is the purpose of the MessageStore in the chat client?