Building a Simple Python Chat Room with Sockets: A Step-by-Step Guide :
In today’s world of fast-paced communication, creating a chat room where multiple users can connect and chat in real-time can be a great project to enhance your coding skills. In this tutorial, we’ll walk you through the process of building a simple, socket-based chat room server in Python, allowing multiple clients to connect and communicate with each other.
We’ll use Python’s built-in socket module, which provides low-level networking capabilities, and the colorama package to make our output more visually engaging by assigning unique colors to each user.
Getting Started :
Before we begin, make sure you have Python installed on your machine. Additionally, you’ll need to install the colorama package, which allows you to change text color in the terminal. You can install it using:
pip install colorama
Overview –
Our chat room will consist of two key components:
- Server: The server listens for incoming client connections and manages message broadcasting.
- Client: Each client connects to the server, sends messages, and listens for messages from other clients.
Let’s dive into the code!
Server Code –
The server performs two critical tasks:
- Listening for connections: When a new client connects, the server adds the client to the collection of active clients.
- Message broadcasting: Once connected, the server creates a new thread for each client to listen for incoming messages, broadcasting them to all connected clients.
Here’s how we can set up the server:
import socket
from threading import Thread
# Server configuration
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5002
separator_token = "<SEP>"
# Store client sockets
client_sockets = set()
# Initialize the server socket
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
def listen_for_client(cs):
"""Function to continuously listen for messages from a specific client."""
while True:
try:
# Receive message from client
msg = cs.recv(1024).decode()
except Exception as e:
# Handle client disconnection
print(f"[!] Error: {e}")
client_sockets.remove(cs)
break
else:
# Replace separator token and broadcast the message
msg = msg.replace(separator_token, ": ")
for client_socket in client_sockets:
client_socket.send(msg.encode())
while True:
# Accept new client connections
client_socket, client_address = s.accept()
print(f"[+] {client_address} connected.")
# Add the new client socket to the set
client_sockets.add(client_socket)
# Start a thread to listen to messages from this client
t = Thread(target=listen_for_client, args=(client_socket,))
t.daemon = True
t.start()
# Close all sockets upon server shutdown
for cs in client_sockets:
cs.close()
s.close()
How It Works:
- The server listens on port 5002, waiting for incoming client connections.
- Each connected client is assigned its own thread to listen for incoming messages.
- These messages are then broadcasted to all connected clients.
- If a client disconnects or an error occurs, the server removes the client from the active socket list.
Client Code –
Each client will:
- Connect to the server.
- Listen for incoming messages from the server.
- Send messages to the server to be broadcast to all other connected clients.
Here’s how we can set up the client:
import socket
import random
from threading import Thread
from datetime import datetime
from colorama import Fore, init
# Initialize colorama
init()
# Available colors for the chat clients
colors = [
Fore.BLUE, Fore.CYAN, Fore.GREEN, Fore.LIGHTBLACK_EX, Fore.LIGHTBLUE_EX,
Fore.LIGHTCYAN_EX, Fore.LIGHTGREEN_EX, Fore.LIGHTMAGENTA_EX,
Fore.LIGHTRED_EX, Fore.LIGHTWHITE_EX, Fore.LIGHTYELLOW_EX, Fore.MAGENTA,
Fore.RED, Fore.WHITE, Fore.YELLOW
]
client_color = random.choice(colors)
# Server details
SERVER_HOST = "127.0.0.1"
SERVER_PORT = 5002
separator_token = "<SEP>"
# Initialize the client socket
s = socket.socket()
print(f"[*] Connecting to {SERVER_HOST}:{SERVER_PORT}...")
s.connect((SERVER_HOST, SERVER_PORT))
print("[+] Connected.")
# Prompt for user's name
name = input("Enter your name: ")
def listen_for_messages():
"""Function to listen for incoming messages from the server."""
while True:
message = s.recv(1024).decode()
print("\n" + message)
# Start a thread to listen for messages from the server
t = Thread(target=listen_for_messages)
t.daemon = True
t.start()
while True:
# Get user input
to_send = input()
# If the user wants to exit
if to_send.lower() == 'q':
break
# Add timestamp and format the message
date_now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
to_send = f"{client_color}[{date_now}] {name}{separator_token}{to_send}{Fore.RESET}"
# Send the message to the server
s.send(to_send.encode())
# Close the connection
s.close()
Key Features:
- Each client connects to the server using the server’s IP address and port. Clients are assigned random colors to distinguish their messages in the chat.
- The client continuously listens for incoming messages from the server and displays them in real-time.
Running the Chat Room Start by running the server script (server.py) on your machine.
- The server will listen for incoming connections:
python server.py
- Run the client script (client.py) on the same machine or any machine in the same network. Each client will prompt you to enter a name, then you can start chatting:
python client.py
You can connect multiple clients and see their messages broadcasted in the terminal, each with a unique color.
Connecting Remotely –
To connect from different machines, ensure that the server’s firewall and router settings allow traffic on port 5002.
You can achieve this using ufw (Uncomplicated Firewall) for Linux:
sudo ufw allow 5002
If you’re hosting the server at home, you may need to modify your router’s settings to open the necessary port for external access.
Conclusion –
With just a few lines of Python code, you can create a fully functional chat room server and client using sockets.
This project is an excellent way to understand how network communication works and can be further expanded with additional features, such as notifications when a new user joins, private messaging, or a user authentication system.
Feel free to explore more advanced networking topics like file transfers, remote shell creation, or building more sophisticated chat applications!
Happy coding!

