Building a Real-Time Chat Application with Python and WebSockets
Learn how to build a simple real-time chat application using Python and WebSockets. This beginner-friendly tutorial walks you through setting up a WebSocket server and creating a simple client to exchange messages instantly.
Real-time communication is essential in many modern web applications, and WebSockets provide a perfect way to achieve this. In this tutorial, we'll create a simple real-time chat app using Python. We'll use the "websockets" library to handle WebSocket connections easily.
First, ensure you have Python installed on your computer. Then, install the websockets library using pip:
pip install websocketsNext, let's create a basic WebSocket server. The server will listen for clients connecting, receive messages from them, and broadcast those messages to all connected clients.
import asyncio
import websockets
# A set to store all connected clients
connected_clients = set()
async def chat_server(websocket, path):
# Register client connection
connected_clients.add(websocket)
try:
async for message in websocket:
# When a message is received, send it to all clients
for client in connected_clients:
if client != websocket: # Optionally exclude sender
await client.send(message)
except websockets.exceptions.ConnectionClosed:
pass
finally:
# Unregister client on disconnect
connected_clients.remove(websocket)
# Start the server
start_server = websockets.serve(chat_server, "localhost", 6789)
print("Chat server started on ws://localhost:6789")
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()This code starts a WebSocket server on localhost at port 6789. When clients connect, they are added to a set, and whenever a message is received from any client, it is broadcast to the others.
Now, let’s create a simple client script to connect to this server and send messages. This client will also listen for messages and print them.
import asyncio
import websockets
async def chat_client():
uri = "ws://localhost:6789"
async with websockets.connect(uri) as websocket:
# Run two tasks: one to send messages and another to receive
async def send_msg():
while True:
message = input("You: ")
await websocket.send(message)
async def recv_msg():
while True:
message = await websocket.recv()
print(f"Friend: {message}")
await asyncio.gather(send_msg(), recv_msg())
asyncio.get_event_loop().run_until_complete(chat_client())Open multiple terminal windows to run this client script and connect to the server. You can now chat in real time between these terminal clients!
This simple example shows the power of WebSockets for real-time communication. You can expand this by adding features like handling usernames, storing message history, or integrating with a web UI.
Remember, WebSocket servers can also be deployed on the web and accessed from browsers using JavaScript clients, making your chat application accessible anywhere.
Feel free to explore and improve this project as your Python and asynchronous programming skills grow!