Skip to content
Python

Building a Simple Python Chat Room with Multi-Client Socket Programming

This guide walks you through creating a basic chat room in Python using sockets and threading. You will learn how to design the architecture, implement a multi-client server, build an interactive client, handle usernames, and test or enhance your chat room.

CodingBowl··2 min read
Photo by Rémi Walle on Unsplash

This guide walks you through creating a basic chat room in Python using sockets and threading. You will learn how to design the architecture, implement a multi-client server, build an interactive client, handle usernames, and test or enhance your chat room.

1. Design the Chat Room Architecture

Plan how the server will manage multiple clients, broadcast messages, and handle connections/disconnections. The server will use threads to handle each client and a shared list to keep track of connected clients.

`
# Pseudocode for server architecture
clients = []

def handle_client(client_socket):
while connected:
message = client_socket.recv()
broadcast(message)

def broadcast(message):
for client in clients:
client.send(message)
`

2. Implement the Multi-Client Chat Server

Write a Python server that accepts multiple clients, receives messages, and broadcasts them to all connected clients using threads.

`
# server.py
import socket
import threading

HOST = '127.0.0.1'
PORT = 5555

def handle_client(conn, addr):
print(f"Connected by {addr}")
data = conn.recv(1024)
if data:
print(f"Received from {addr}: {data.decode()}")
conn.sendall(b"Hello from server!")
conn.close()

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
print("Server listening...")
while True:
conn, addr = s.accept()
thread = threading.Thread(target=handle_client, args=(conn, addr))
thread.start()
`

3. Develop the Interactive Chat Client

Create a Python client that connects to the server, sends user input, and displays messages from other users in real time.

`
# client.py
import socket
import threading

HOST = '127.0.0.1'
PORT = 5555

def receive_messages(sock):
while True:
try:
message = sock.recv(1024)
if not message:
break
print(message.decode())
except:
break

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

threading.Thread(target=receive_messages, args=(client,), daemon=True).start()

while True:
msg = input()
if msg.lower() == 'exit':
break
client.sendall(msg.encode())

client.close()
`

4. Handle Usernames and Message Formatting

Add support for clients to set usernames and format messages for clarity in the chat room.

`
# In client.py, prompt for username
username = input("Enter your username: ")
client.sendall(username.encode())

# In server.py, receive and store username
usernames = {}

def handle_client(client_socket):
username = client_socket.recv(1024).decode()
usernames[client_socket] = username
welcome = f"{username} has joined the chat."
broadcast(welcome.encode(), client_socket)
while True:
try:
message = client_socket.recv(1024)
if not message:
break
formatted = f"{username}: {message.decode()}"
broadcast(formatted.encode(), client_socket)
except:
break
clients.remove(client_socket)
client_socket.close()
broadcast(f"{username} has left the chat.".encode(), client_socket)
`

5. Test and Enhance the Chat Room

Run the server and multiple clients, test message broadcasting, and discuss possible enhancements like private messaging or a simple GUI.

  • Start the server: python server.py

  • Open multiple terminals and run python client.py in each.

  • Test sending messages between clients.