A Python chat server (socket programming)
an advanced project for students who have finished the basic course and the Python for the web lessons – usually secondary school. For grades 5–8, projects with graphics and the micro:bit are a better choice.
In this project we will create a simple chat server using Python and the socket module. The goal is for several users to be able to send messages between clients through the server.
This project is an excellent example for learning the basics of network programming and socket communication in Python.
How does the system work?
- The server keeps a list of connected clients
- Each client runs in a separate thread
- A message is sent to all clients (broadcast)
- Sockets make real-time communication possible
- Discord
- WhatsApp Web
- online games
Where is a system like this used?
- chat applications (WhatsApp, Messenger)
- online games (multiplayer)
- live notifications
- collaboration tools
Tools you need
- Python 3
- Terminal / Command Prompt
- Basic knowledge of Python functions and loops
Server code
import socket
import threading
# Creating the server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 5555))
server.listen()
clients = []
nicknames = []
def broadcast(message):
for client in clients:
client.send(message)
def handle(client):
while True:
try:
message = client.recv(1024)
if not message: # the client closed the connection
raise ConnectionError
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
nickname = nicknames[index]
broadcast(f'{nickname} has left the chat!'.encode('utf-8'))
nicknames.remove(nickname)
break
def receive():
while True:
client, address = server.accept()
print(f"Connected: {str(address)}")
client.send('NICK'.encode('utf-8'))
nickname = client.recv(1024).decode('utf-8')
nicknames.append(nickname)
clients.append(client)
print(f'The user\'s nickname is {nickname}')
broadcast(f'{nickname} has joined the chat!'.encode('utf-8'))
client.send('Connected to the server!'.encode('utf-8'))
thread = threading.Thread(target=handle, args=(client,))
thread.start()
print("The server is running...")
receive()
Mini project – The client
For the chat to work, we need clients that connect to the server.
import socket
import threading
nickname = input("Choose a nickname: ")
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 5555))
def receive():
while True:
try:
message = client.recv(1024).decode('utf-8')
if not message: # the server closed the connection
raise ConnectionError
if message == 'NICK':
client.send(nickname.encode('utf-8'))
else:
print(message)
except:
print("Error!")
client.close()
break
def write():
while True:
message = f'{nickname}: {input("")}'
client.send(message.encode('utf-8'))
receive_thread = threading.Thread(target=receive)
receive_thread.start()
write_thread = threading.Thread(target=write)
write_thread.start()
How does this project work?
- The server accepts connections from several clients
- Messages are forwarded to all clients in real time
- Users can see who has joined or left the chat
How can you improve the project?
- add a login system
- move to WebSocket (FastAPI / Django Channels)
- make a GUI client (Tkinter)
- deploy to a server (VPS / cloud)
Limitations of this project
- it does not use authentication
- messages are not encrypted
- it works only locally (localhost)
Related lessons and projects
Frequently asked questions
Does this chat server work over the internet?
This example works locally on one computer. To work over the internet you need a public IP address and port forwarding on the router.
What is a socket in Python?
A socket is a point of communication between a server and a client.
Can we add a GUI client?
Yes, you can use Tkinter or PyQt to show the messages visually.
