Creating a real-time chat application from scratch using WebSockets in Python is a powerful way to understand how bidirectional communication works on the web. This guide shows you how to implement a simple WebSocket-based chat server and client without relying on frameworks like Django or Flask.
What You’ll Need
- Python 3.7+
-
websockets
library (pip install websockets
) - Basic HTML/CSS for the frontend
Step 1: Set Up a Simple WebSocket Server
import asyncio
import websockets
connected_clients = set()
async def echo(websocket, path):
connected_clients.add(websocket)
try:
async for message in websocket:
for client in connected_clients:
if client != websocket:
await client.send(message)
except websockets.exceptions.ConnectionClosed:
pass
finally:
connected_clients.remove(websocket)
start_server = websockets.serve(echo, "localhost", 6789)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
This server accepts new connections and relays messages to all other clients.
Step 2: Create the HTML Chat Interface
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
</head>
<body>
<h2>Chat App</h2>
<input id="msg" type="text" placeholder="Type your message..." />
<button onclick="sendMessage()">Send</button>
<ul id="chat"></ul>
<script>
const ws = new WebSocket("ws://localhost:6789");
const chat = document.getElementById("chat");
ws.onmessage = function(event) {
const li = document.createElement("li");
li.textContent = event.data;
chat.appendChild(li);
};
function sendMessage() {
const input = document.getElementById("msg");
ws.send(input.value);
input.value = "";
}
</script>
</body>
</html>
This frontend connects to the server and allows message sending and receiving in real-time.
Step 3: Run the App
1. Run the Python server: python chat_server.py
2. Open the HTML file in multiple browser tabs.
3. Type messages and see them appear across all clients instantly.
Security Considerations
- Use authentication for production environments.
- Consider using secure WebSockets (
wss://
) over HTTPS. - Validate all messages on the server side.
Conclusion
This simple yet powerful project introduces you to the inner workings of WebSockets and real-time messaging. With no frameworks involved, you gain full control over the communication pipeline.
If you found this helpful, please consider supporting my work: buymeacoffee.com/hexshift
Top comments (0)