In this article, you’ll learn how to make a real-time chat room using Python’s asyncio and websockets libraries. This method is better than old ways of using threads or select because it’s faster, more efficient and works like modern chat apps such as Slack or Discord.
Why switch from old socket programming?
Let’s understand why developers are moving towards modern approaches for building real-time applications.
Old methods using socket, select and _thread:
- Struggle when many users connect at once.
- Don’t work well with modern web tools like WebSockets.
- Are harder to connect with frontend stuff (like React or Vue).
- Need a lot of extra code to handle multiple users.
Modern way is better because:
- asyncio handles many users smoothly.
- WebSocket support is built-in—great for real-time web chats.
- Easy to connect with modern frontends.
- Code is simpler and easier to manage.
Project Structure
Let's understand the project structure:
chat-room/
├── server.py # WebSocket-based server
├── client.html # Simple frontend client (runs in browser)
├── README.md
Prerequisites:
Install the required library:
pip install websockets
WebSocket chat server(server.py)
import asyncio
import websockets
clients = set()
async def handle(ws):
clients.add(ws)
try:
async for msg in ws:
await asyncio.gather(*[
c.send(msg) for c in clients if c != ws
])
except websockets.exceptions.ConnectionClosed:
pass
finally:
clients.remove(ws)
async def main():
async with websockets.serve(handle, "localhost", 6789):
print("Server running at ws://localhost:6789")
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(main())
Explanation:
- clients: A set to store active WebSocket connections.
- handle(ws) registers the client and listens for messages.
- asyncio.gather(...) broadcasts the message to all other connected clients.
- websockets.serve(...) starts the WebSocket server on localhost:6789
Websocket Client( client.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Chat</title>
</head>
<body>
<h2>Chat Room</h2>
<textarea id="c" cols="50" rows="15" readonly></textarea><br>
<input type="text" id="m" placeholder="Type message..." />
<button onclick="send()">Send</button>
<script>
const c = document.getElementById("c");
const m = document.getElementById("m");
const ws = new WebSocket("ws://localhost:6789");
ws.onmessage = e => c.value += e.data + "\n";
function send() {
const txt = m.value;
ws.send(txt);
c.value += "<You>: " + txt + "\n";
m.value = "";
}
</script>
</body>
</html>
Explanation:
- A textarea shows the chat history (read-only).
- An input field lets the user type messages.
- WebSocket("ws://localhost:6789") connects to the Python server.
- ws.send(txt) sends your message to the server.
- ws.onmessage appends received messages to the chat log.
Running the Chat room
1. Start the WebSocket Server:
python server.py
2. Open the Client:
- Double-click client.html or open it via a local server (python -m http.server).
- Open in multiple browser tabs to simulate multiple users.