Building a Simple TCP Chat Application

A step-by-step tutorial showing how to build a chat application using our TCP implementation

Introduction

In this tutorial, we’ll build a simple chat application using our TCP server and client implementations. This will demonstrate a practical application of the TCP protocol and show how our library can be used to build real-world applications.

Let’s start by importing the necessary modules:

from python_tcp.core import *
from python_tcp.server import EventDrivenTCPServer
from python_tcp.client import EventDrivenTCPClient
import threading
import time
import json
import datetime

1. Designing the Chat Protocol

First, let’s design a simple protocol for our chat application. We’ll use JSON to format our messages with the following structure:

{
    "type": "message_type",
    "username": "sender_username",
    "content": "message_content",
    "timestamp": unix_timestamp
}

Message types will include: - join: User joining the chat - leave: User leaving the chat - message: Regular chat message - users: List of active users (sent by server)

2. Implementing the Chat Server

Let’s start by implementing the chat server:


source

ChatServer

 ChatServer (host='127.0.0.1', port=0)

A simple chat server using our TCP implementation.

3. Implementing the Chat Client

Now, let’s implement the chat client:


source

ChatClient

 ChatClient (username)

A simple chat client using our TCP implementation.

4. Using the Chat Application

Now let’s demonstrate how to use our chat application:

def chat_demo():
    # Start the chat server
    server = ChatServer(port=8000)
    server_port = server.start()
    
    try:
        # Create and connect multiple chat clients
        clients = []
        usernames = ["Alice", "Bob", "Charlie"]
        
        for username in usernames:
            # Create a message handler for this client
            def create_message_handler(name):
                return lambda msg: print(f"[{name}] {msg}")
            
            # Create and set up the client
            client = ChatClient(username)
            client.set_message_callback(create_message_handler(username))
            
            # Connect to the server
            if client.connect(LOCALHOST, server_port):
                # Join the chat
                client.join()
                clients.append(client)
                
                # Give some time for the join process
                time.sleep(0.5)
            else:
                print(f"Failed to connect client {username}")
        
        # Wait a moment for all clients to connect
        time.sleep(1)
        
        # Send some messages
        clients[0].send_message("Hello everyone!")
        time.sleep(0.5)
        
        clients[1].send_message("Hi Alice, how are you?")
        time.sleep(0.5)
        
        clients[2].send_message("Hey folks, nice to meet you all!")
        time.sleep(0.5)
        
        clients[0].send_message("I'm doing well, thanks Bob!")
        time.sleep(0.5)
        
        # Have one client leave
        print("\nCharlie is leaving the chat...")
        clients[2].leave()
        time.sleep(1)
        
        # Continue the conversation
        clients[0].send_message("Looks like Charlie had to go.")
        time.sleep(0.5)
        
        clients[1].send_message("Yes, too bad. Anyway, nice chatting with you Alice!")
        time.sleep(0.5)
        
        # Close remaining clients
        for client in clients[:-1]:  # Charlie already left
            client.leave()
            time.sleep(0.5)
        
    finally:
        # Stop the server
        server.stop()

# Uncomment to run the demo
# chat_demo()

5. Building a Command-Line Chat Interface

Finally, let’s create a simple command-line interface for our chat application:


source

run_chat_client

 run_chat_client ()

Run a command-line chat client.


source

run_chat_server

 run_chat_server ()

Run a chat server.

Define main entry points


source

start_server

 start_server ()

Entry point for starting a chat server.


source

start_client

 start_client ()

Entry point for starting a chat client.

Conclusion

In this tutorial, we’ve built a complete chat application using our TCP server and client implementations. This demonstrates how the TCP protocol can be used to build real-world applications that require reliable communication between multiple clients and a server.

The chat application includes: - A TCP-based server that handles multiple client connections - A JSON-based protocol for exchanging messages - Support for joining/leaving the chat - User presence tracking - Message broadcasting - Error handling - A simple command-line interface

This demonstrates the practical application of the concepts we’ve learned about TCP networking.