๐ฏ Project Objective
Build a real-time chat application using Python sockets that allows multiple users to connect to a common server and exchange messages instantly.
๐ง Skills Youโll Learn
- Socket programming (TCP communication)
- Client-server architecture
- Multithreading for handling multiple users
- GUI design using Tkinter (optional)
- Network message broadcasting
๐๏ธ Project Overview
Youโll create:
- Server script (
server.py) โ handles connections and broadcasts messages to all clients. - Client script (
client.py) โ allows users to send and receive messages in real-time.
This setup works locally (LAN) or across a Wi-Fi network if both devices are connected to the same router.
โ๏ธ Technology Stack
| Library | Purpose |
|---|---|
socket | Enables network communication between server and clients |
threading | Allows concurrent handling of multiple clients |
tkinter (optional) | GUI for chat interface |
sys, os | Command-line control and system utilities |
๐งพ File 1 โ Server (server.py)
import socket
import threading
# Server Configuration
HOST = '127.0.0.1' # Localhost (use your IP for LAN)
PORT = 55555
# Create Socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((HOST, PORT))
server.listen()
clients = []
nicknames = []
def broadcast(message):
"""Send message to all connected clients"""
for client in clients:
client.send(message)
def handle(client):
"""Handle messages from a single client"""
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
# Remove client if connection is lost
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():
"""Accept new client connections"""
print("Server is running and listening...")
while True:
client, address = server.accept()
print(f"Connected with {str(address)}")
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!".encode('utf-8'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
receive()
๐ป File 2 โ Client (client.py)
import socket
import threading
nickname = input("Choose your nickname: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))
def receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if message == 'NICK':
client.send(nickname.encode('utf-8'))
else:
print(message)
except:
print("An error occurred!")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")}'
client.send(message.encode('utf-8'))
# Threads for reading and writing
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
๐งฉ How It Works
๐น Step 1 โ Start the Server
Run server.py in one terminal:
Server is running and listening...
๐น Step 2 โ Start Multiple Clients
Run client.py in separate terminals (or computers on the same network).
Example interaction:
User1: Hello everyone!
User2: Hi, User1 ๐
User3: How are you all?
๐งฑ Architecture Diagram
โโโโโโโโโโโโโโโโโโโโโโ
โ Server (Host) โ
โ โโโโโโโโโโโโโโโโ โ
โ socket + threads โ
โโโโโโโโโโฌโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโ
โ โ โ
โผ โผ โผ
Client 1 Client 2 Client 3
(User1) (User2) (User3)
๐ LAN Setup (Optional)
If you want to chat across computers on the same Wi-Fi:
- Replace
HOST = '127.0.0.1'with your local IP address (found viaipconfigorifconfig). - Run the server on your main PC.
- Connect from other computers using that IP.
๐ก Bonus: GUI Chat Client (Optional)
You can add this using tkinter for a polished interface:
from tkinter import *
import threading, socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55555))
def receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
chat_box.insert(END, message + '\n')
except:
print("Disconnected")
client.close()
break
def send_message():
message = f"{nickname.get()}: {msg_entry.get()}"
client.send(message.encode('utf-8'))
msg_entry.delete(0, END)
root = Tk()
root.title("Python Chat App")
chat_box = Text(root, bg="white", width=50, height=15)
chat_box.pack()
msg_entry = Entry(root, width=40)
msg_entry.pack(side=LEFT, padx=5)
send_btn = Button(root, text="Send", command=send_message)
send_btn.pack(side=LEFT)
nickname = StringVar()
nickname.set(input("Enter your nickname: "))
threading.Thread(target=receive).start()
root.mainloop()
๐ง Learning Outcomes
After completing this project, youโll:
- Understand TCP/IP communication
- Learn to use threads for concurrency
- Manage multiple clients in real-time
- Build real network-based applications
๐ Project Enhancements (Next Steps)
| Feature | Description |
|---|---|
| ๐๏ธ Private Chat | Allow direct messaging between two users |
| ๐งพ Message History | Save all messages in a text or SQLite file |
| ๐ Encryption | Secure chat messages with cryptography |
| ๐ Web Version | Convert to Flask + SocketIO for browser chat |
| ๐จ GUI Styling | Add emojis, timestamps, themes |

Leave a Reply