Building a WebSocket server in Python allows you to establish a continuous and bidirectional communication channel between the server and clients. Below is a detailed guide explaining each component to construct a basic WebSocket server using the websockets
library.
Step 1: Install the WebSocket Library
To begin, you need to install the websockets
library by executing the following command in the terminal:
pip install websockets
Step 2: Creating the WebSocket Server
Here's an example of how to build a WebSocket server in Python:
import asyncio
import websockets
# WebSocket connection handling function
async def handle_connection(websocket, path):
async for message in websocket:
# Process the data and send a response
response = f"Server received: {message}"
await websocket.send(response)
# Initialize the WebSocket server
start_server = websockets.serve(handle_connection, "localhost", 8765)
# Run the server within the event loop
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
In the code snippet:
-
async def handle_connection(websocket, path):
: This function handles WebSocket connections. Each time a client connects, this function is called to manage the communication. -
async for message in websocket:
: This loop iterates to listen for messages from the client through the WebSocket connection. -
await websocket.send(response)
: This function sends a response from the server back to the client via the WebSocket connection. -
websockets.serve(handle_connection, "localhost", 8765)
: This function creates a WebSocket server that listens for connections on thelocalhost
address and port8765
.
Step 3: Testing the Server
After deploying the server code, it will listen for connections from clients on port 8765. You can test the server by connecting to it using WebSocket client code or online testing tools.
Conclusion
By following these steps, you've successfully built a simple WebSocket server in Python. This server provides the foundation for creating real-time applications and interactions between the server and clients using the WebSocket protocol.