Easy Chat Client and Server

Written by

in

Easy Chat Client and Server Building a custom chat application is the ultimate rite of passage for software developers. It transforms abstract networking concepts into a tangible, real-time tool you can actually use.

By utilizing Python and its built-in socket library, you can build a fully functional, multi-user chat server and client in under 100 lines of code. Here is how network communication works and how to build your own lightweight chat system. Understanding Network Sockets

Before writing code, it helps to understand how computers talk to each other. Network communication relies on Sockets, which act as internal endpoints for sending and receiving data.

To create a chat system, we use a architecture containing two distinct roles:

The Server: This program runs constantly on a specific machine. It listens for incoming connection requests from users, accepts them, and broadcasts messages so everyone in the chat can see them.

The Client: This is the program the user interacts with. It connects to the server’s address, sends the user’s typed messages, and displays messages received from other users.

We will use TCP (Transmission Control Protocol) for this project. TCP is a connection-oriented protocol, meaning it guarantees that data arrives safely, completely, and in the correct order—making it perfect for text communication. Part 1: The Multi-Threaded Server

A basic server can only handle one action at a time. If it is waiting for User A to type, User B is blocked from sending a message. To fix this, we use threading. Threading allows the server to spin up a separate, isolated background task for every connected user. Create a file named server.py and add the following code:

import socket import threading # Server configuration HOST = ‘127.0.0.1’ # Localhost (your own computer) PORT = 55555 # Unprivileged port to avoid system conflicts # Initialize the TCP socket server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.bind((HOST, PORT)) server.listen() # Lists to track active connections and their usernames clients = [] nicknames = [] def broadcast(message): “”“Sends a message to all currently connected clients.”“” for client in clients: try: client.send(message) except: # Remove broken connections safely index = clients.index(client) clients.remove(client) client.close() nickname = nicknames[index] nicknames.remove(nickname) def handle_client(client): “”“Handles the continuous communication lifecycle of a single client.”“” while True: try: # Receive data from the client (up to 1024 bytes) message = client.recv(1024) if not message: raise Exception(“Disconnected”) broadcast(message) except: # Handle client disconnection gracefully if client in clients: index = clients.index(client) clients.remove(client) client.close() nickname = nicknames[index] broadcast(f’{nickname} left the chat.‘.encode(‘utf-8’)) nicknames.remove(nickname) break def receive(): “”“Main loop to accept new incoming client connections.”“” print(f”Server is running and listening on {HOST}:{PORT}…“) while True: client, address = server.accept() print(f”Connected with structural address {str(address)}“) # Request and store the user’s nickname client.send(‘NICK’.encode(‘utf-8’)) nickname = client.recv(1024).decode(‘utf-8’) nicknames.append(nickname) clients.append(client) print(f”Nickname of the client is {nickname}“) broadcast(f”{nickname} joined the chat!“.encode(‘utf-8’)) client.send(‘Connected to the server! Ready to chat.’.encode(‘utf-8’)) # Start a dedicated thread for this specific client thread = threading.Thread(target=handle_client, args=(client,)) thread.start() if name == “main”: receive() Use code with caution. Part 2: The Interactive Client

The client also needs threading. It must continuously listen for incoming messages from the server while simultaneously waiting for the user to type into the console. Create a second file named client.py and add this code: Use code with caution. How to Run Your Chat Application

To see your creation in action, you will need to open multiple terminal/command prompt windows on your machine:

Start the Server: Open your first terminal window, navigate to the folder containing your files, and run: python server.py Use code with caution. Launch Client 1: Open a second terminal window and run: python client.py Use code with caution. Type a nickname (e.g., “Alice”) when prompted. Launch Client 2: Open a third terminal window and run: python client.py Use code with caution. Type a different nickname (e.g., “Bob”).

Now, type a message in Alice’s terminal and hit Enter. You will instantly see it pop up in Bob’s terminal window. Next Steps for Customization

This script provides a minimal backbone for network programming. Once you have it running smoothly, you can expand it with new features to learn more advanced concepts:

GUI Integration: Use Python’s built-in tkinter library to build a visual window interface instead of a command-line interface.

Private Messaging: Add a syntax like /msg username message to send direct whispers to specific users instead of broadcasting to everyone.

Encryption: Implement the cryptography library to encrypt messages before they leave the client, making your chat secure from data sniffers. If you want to take this project further, tell me:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *