Real-time Chat Application (WebSocket)
Abstract
Build a Real-time Chat Application using WebSocket for real-time communication between clients. The app includes server and client implementations for sending and receiving messages. This project demonstrates WebSocket programming, concurrency, and network communication in Python.
Prerequisites
- Python 3.6 or above
- Text Editor or IDE
- Basic understanding of Python syntax
- Familiarity with WebSocket programming
- Knowledge of asyncio for concurrency
Getting Started
Creating a new project
- Create a new project folder and name it
real_time_chat_application
real_time_chat_application
. - Create a new file inside the folder and name it
real_time_chat_application.py
real_time_chat_application.py
. - Open the project folder in your favorite text editor or IDE.
- Copy the code below and paste it into the
real_time_chat_application.py
real_time_chat_application.py
file.
Write the code
⚙️ real_time_chat_application.py
real_time_chat_application.py
"""
Real-time Chat Application (WebSocket)
A Python application that enables real-time communication between clients using WebSocket.
Features include:
- Real-time messaging between multiple clients.
- Server-side implementation using `websockets` library.
- Client-side implementation for sending and receiving messages.
"""
import asyncio
import websockets
connected_clients = set()
async def handle_client(websocket, path):
"""Handle incoming messages from clients and broadcast them."""
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)
async def broadcast(message):
"""Send a message to all connected clients."""
if connected_clients: # Ensure there are clients to broadcast to
await asyncio.wait([client.send(message) for client in connected_clients])
async def main():
"""Start the WebSocket server."""
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
real_time_chat_application.py
"""
Real-time Chat Application (WebSocket)
A Python application that enables real-time communication between clients using WebSocket.
Features include:
- Real-time messaging between multiple clients.
- Server-side implementation using `websockets` library.
- Client-side implementation for sending and receiving messages.
"""
import asyncio
import websockets
connected_clients = set()
async def handle_client(websocket, path):
"""Handle incoming messages from clients and broadcast them."""
connected_clients.add(websocket)
try:
async for message in websocket:
print(f"Received message: {message}")
await broadcast(message)
except websockets.ConnectionClosed:
print("Client disconnected")
finally:
connected_clients.remove(websocket)
async def broadcast(message):
"""Send a message to all connected clients."""
if connected_clients: # Ensure there are clients to broadcast to
await asyncio.wait([client.send(message) for client in connected_clients])
async def main():
"""Start the WebSocket server."""
server = await websockets.serve(handle_client, "localhost", 8765)
print("Server started on ws://localhost:8765")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
Key Features
- Real-time messaging between multiple clients
- Server-side implementation using
websockets
websockets
library - Client-side implementation for sending and receiving messages
- Concurrency using asyncio
Explanation
Server Implementation
The server handles incoming messages and broadcasts them to all clients:
real_time_chat_application.py
async def handle_client(websocket, path):
connected_clients.add(websocket)
async for message in websocket:
await broadcast(message)
real_time_chat_application.py
async def handle_client(websocket, path):
connected_clients.add(websocket)
async for message in websocket:
await broadcast(message)
Broadcasting Messages
Messages are sent to all connected clients:
real_time_chat_application.py
async def broadcast(message):
await asyncio.wait([client.send(message) for client in connected_clients])
real_time_chat_application.py
async def broadcast(message):
await asyncio.wait([client.send(message) for client in connected_clients])
Running the Application
- Save the file.
- Install required dependencies:
pip install websockets
pip install websockets
- Run the server:
python real_time_chat_application.py
python real_time_chat_application.py
Conclusion
This Real-time Chat Application project is a great way to learn about WebSocket programming and concurrency in Python. You can extend it by adding a GUI, message history, or user authentication.
Was this page helpful?
Let us know how we did