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
Building a Simple TCP Chat Application
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:
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:
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:
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
= ChatServer(port=8000)
server = server.start()
server_port
try:
# Create and connect multiple chat clients
= []
clients = ["Alice", "Bob", "Charlie"]
usernames
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
= ChatClient(username)
client
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
0.5)
time.sleep(else:
print(f"Failed to connect client {username}")
# Wait a moment for all clients to connect
1)
time.sleep(
# Send some messages
0].send_message("Hello everyone!")
clients[0.5)
time.sleep(
1].send_message("Hi Alice, how are you?")
clients[0.5)
time.sleep(
2].send_message("Hey folks, nice to meet you all!")
clients[0.5)
time.sleep(
0].send_message("I'm doing well, thanks Bob!")
clients[0.5)
time.sleep(
# Have one client leave
print("\nCharlie is leaving the chat...")
2].leave()
clients[1)
time.sleep(
# Continue the conversation
0].send_message("Looks like Charlie had to go.")
clients[0.5)
time.sleep(
1].send_message("Yes, too bad. Anyway, nice chatting with you Alice!")
clients[0.5)
time.sleep(
# Close remaining clients
for client in clients[:-1]: # Charlie already left
client.leave()0.5)
time.sleep(
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:
run_chat_client
run_chat_client ()
Run a command-line chat client.
run_chat_server
run_chat_server ()
Run a chat server.
Define main entry points
start_server
start_server ()
Entry point for starting a chat server.
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.