Introduction to WebSockets
Real-time data powers much of modern software, including live stock prices, chat applications, and collaborative tools. To build these systems, you need to understand how real-time communication works. In this article, we’ll explore Python’s websockets library and move into FastAPI, where many Python backends live.
WebSocket Connections and Methods
A WebSocket connection enables bi-directional communication between a client and a server. Once a connection is established, both sides can communicate freely without either having to ask first.
The core methods provided by Python’s websockets library include:
- websockets.serve(…): starts a WebSocket server.
- websockets.connect(…): connects to a WebSocket server.
- websockets.send(…): sends a message from either side.
- websockets.recv(): receives a message from client or server.
How to Build Your First WebSocket in Python
To set up a simple server and client, and exchange messages over a WebSocket connection, follow these steps:
- Install the WebSockets package using pip: pip install websockets
- Create a WebSocket server using the websockets library.
- Set up a client to connect to the server.
Here’s an example of a simple WebSocket server:
import asyncio
import websockets
async def handler(connection):
print("Client connected")
message = await connection.recv()
print("Received from client:", message)
await connection.send("Hello client!")
async def main():
async with websockets.serve(handler, "localhost", 8000):
print("Server running at ws://localhost:8000")
await asyncio.sleep(30)
asyncio.run(main())
File Transfer Over WebSockets
WebSockets support raw bytes, which means you can send files directly over the connection. Here’s an example of how a client can send a file to a server over a WebSocket connection:
import asyncio
import websockets
async def file_handler(ws):
print("Client connected, waiting for file...")
file_bytes = await ws.recv() # receive bytes
with open("received_file.png", "wb") as f:
f.write(file_bytes)
print("File received and saved!")
await ws.send("File received successfully!")
async def main():
async with websockets.serve(file_handler, "localhost", 8000):
print("Server running on ws://localhost:8000")
await asyncio.sleep(50) # keep server alive
asyncio.run(main())
WebSockets in FastAPI
FastAPI provides built-in support for WebSockets. Here’s an example of how to use WebSockets in FastAPI:
from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}")
Conclusion
In conclusion, WebSockets provide a powerful way to establish real-time communication between a client and a server. By following the steps outlined in this article, you can build your own WebSocket application using Python and FastAPI.
Remember to keep your WebSocket connections secure by using SSL/TLS encryption and authenticating your clients.
Frequently Asked Questions
- What is a WebSocket?
A WebSocket is a protocol that enables bi-directional communication between a client and a server over the web. - How do I establish a WebSocket connection?
To establish a WebSocket connection, you need to create a WebSocket server and a client that can connect to the server. - Can I send files over a WebSocket connection?
Yes, you can send files over a WebSocket connection using the websockets library. - How do I use WebSockets in FastAPI?
FastAPI provides built-in support for WebSockets. You can use the @app.websocket decorator to define a WebSocket endpoint. - What is the focus keyword for this article?
The focus keyword for this article is WebSockets.








