Building a Real-Time Chat Application with WebSockets in Python
Learn how to create a real-time chat application using Python and WebSockets. This beginner-friendly tutorial guides you step-by-step through building a basic chat server and client.
Real-time communication is essential in modern web applications, especially for chat systems. WebSockets allow full-duplex communication channels over a single long-lived connection between client and server. In this tutorial, we'll build a simple real-time chat application using Python's WebSockets library.
First, let's understand the components: our chat application consists of a server that manages client connections and broadcasts messages, and multiple clients that connect to this server and send/receive messages in real-time.
To get started, you'll need to install the `websockets` package, which is a popular choice for implementing WebSocket servers and clients in Python. You can install it using pip:
pip install websocketsNow, let's create the WebSocket chat server. The server will accept new connections, listen for messages from any client, and broadcast those messages to all other connected clients.
import asyncio
import websockets
connected_clients = set()
async def chat_server(websocket, path):
# Register new client
connected_clients.add(websocket)
try:
async for message in websocket:
# Broadcast received message to all clients
for client in connected_clients:
if client != websocket:
await client.send(message)
except websockets.exceptions.ConnectionClosed:
pass
finally:
# Unregister client
connected_clients.remove(websocket)
async def main():
async with websockets.serve(chat_server, "localhost", 6789):
print("Chat server started on ws://localhost:6789")
await asyncio.Future() # Run forever
if __name__ == "__main__":
asyncio.run(main())This server listens on `ws://localhost:6789`. When a client connects, it adds the connection to a set. Each message received is forwarded to all other connected clients. When a client disconnects, it is removed from the set.
Next, we need a simple client to send and receive messages. Here's an example command-line WebSocket client in Python:
import asyncio
import websockets
async def chat_client():
uri = "ws://localhost:6789"
async with websockets.connect(uri) as websocket:
print("Connected to chat server.")
async def send_messages():
while True:
message = input("")
await websocket.send(message)
async def receive_messages():
async for message in websocket:
print(f"Received: {message}")
await asyncio.gather(send_messages(), receive_messages())
if __name__ == "__main__":
asyncio.run(chat_client())This client connects to the server, reads user input, sends messages, and simultaneously listens for incoming messages to display them. Run the server script first, then start multiple clients to chat.
To sum up, this project helped us understand how to implement WebSocket servers and clients in Python to create a real-time chat application. You can further enhance this by adding user authentication, message history, or a web interface for easier usability.
Happy coding and enjoy building your real-time apps with WebSockets!