WebSocket is a computer communication protocol that provides a full duplex channel for bidirectional communication between a client and a server. Through WebSocket, clients and servers can keep communicating in a long-term connection without establishing a new connection every time. This feature is very useful in applications such as live chat, online games, stock markets, etc.
This article will explain in detail how to implement WebSocket in Python, including the basic concepts of WebSocket, the WebSocket library in Python, simple client and server-side code examples, and some advanced usage scenarios.
1. WebSocket basic concepts
The WebSocket protocol was originally published by the IETF (Internet Engineering Task Force) to provide a more efficient communication protocol that allows two-way communication between clients and servers over a single long connection. WebSocket communications are established by establishing a persistent connection on the HTTP protocol (i.e. WebSocket handshake) and support full duplex communication, that is, data can be sent from the client to the server at the same time or from the server to the client.
WebSocket is very different from the traditional HTTP protocol. HTTP is a request-responsive protocol. Each time a client needs to obtain data, it needs to send a request to the server. WebSocket establishes a communication channel through an initial handshake request, and then both parties can send data at any time.
WebSocket handshake process:
- The client initiates an HTTP request to the server and asks to upgrade to the WebSocket protocol.
- The server responds to the client's request and confirms the upgrade protocol.
- The client and the server establish a WebSocket connection and can start full-duplex communication.
2. Python WebSocket Library
In Python, we usually use the following libraries to implement WebSocket:
- websockets: A lightweight Python WebSocket implementation that supports asynchronous programming.
- : A more advanced library that supports event-driven and automatic reconnection features, and is often used in real-time applications.
- asyncio: Although asyncio itself is not a WebSocket library, it provides basic support for asynchronous programming of WebSocket.
In this article, we will mainly introduce the websockets library and use it to implement WebSocket clients and servers.
3. Install the websockets library
Before using the websockets library, we need to install it first. You can install it through pip:
pip install websockets
4. WebSocket server-side implementation
Create a WebSocket Server
A WebSocket server usually runs on a specific port and waits for a client's connection request. We can implement a simple WebSocket server through the websockets library.
import asyncio import websockets async def handle_connection(websocket, path): # Received the client's message print(f"Connected to {websocket.remote_address}") try: async for message in websocket: print(f"Received message: {message}") # Send a message back to the client await (f"Server received: {message}") except Exception as e: print(f"Error: {e}") finally: print(f"Disconnected from {websocket.remote_address}") async def main(): # Start the WebSocket server and listen to port 8765 server = await (handle_connection, "localhost", 8765) print("WebSocket server started on ws://localhost:8765") await server.wait_closed() # Start the event loop(main())
Code description
handle_connection is an asynchronous function that handles each client connection. Whenever a client connects, the server prints out the received message and returns the message to the client.
() is used to start the WebSocket server and listen for the specified address and port (localhost and 8765 here).
await server.wait_closed() ensures that the server continues to run until it is closed manually.
5. WebSocket client implementation
Create a WebSocket Client
WebSocket clients are used to establish connections with the server and send and receive messages. We use .
import asyncio import websockets async def send_message(): uri = "ws://localhost:8765" async with (uri) as websocket: # Send a message to the server await ("Hello, Server!") print("Message sent to server.") # Receive messages returned by the server response = await () print(f"Received from server: {response}") # Start the event loop(send_message())
Code description
(uri) is used to establish a connection to a WebSocket server. uri is the address of the server, here is ws://localhost:8765.
Use await () to send a message to the server.
Use await () to receive messages from the server.
6. Exception handling
In actual applications, WebSocket connection may fail due to network interruption, server shutdown, etc. We can add appropriate exception handling to both the client and server side.
6.1 Client exception handling
async def send_message(): uri = "ws://localhost:8765" try: async with (uri) as websocket: await ("Hello, Server!") print("Message sent to server.") response = await () print(f"Received from server: {response}") except as e: print(f"Connection closed: {e}") except Exception as e: print(f"Error: {e}") (send_message())
6.2 Server-side exception handling
async def handle_connection(websocket, path): print(f"Connected to {websocket.remote_address}") try: async for message in websocket: print(f"Received message: {message}") await (f"Server received: {message}") except as e: print(f"Connection closed: {e}") except Exception as e: print(f"Error: {e}") finally: print(f"Disconnected from {websocket.remote_address}")
7. Advanced WebSocket
7.1. Broadcast message
If you want the server to broadcast messages to all connected clients, you can maintain a list of clients and send messages.
clients = set() async def handle_connection(websocket, path): (websocket) try: async for message in websocket: print(f"Received message: {message}") # Broadcast messages to all clients for client in clients: if client != websocket: await (f"Broadcast message: {message}") except Exception as e: print(f"Error: {e}") finally: (websocket) print(f"Disconnected from {websocket.remote_address}")
7.2. Certification and Authorization
You can use the initial handshake phase of the WebSocket protocol to authenticate and authorize, such as passing authentication information using HTTP header.
async def handle_connection(websocket, path): headers = websocket.request_headers token = ('Authorization') if token != "expected_token": await ("Unauthorized") await () return print(f"Client authorized with token: {token}") # Process normal messages
8. Summary
This article details how to use the websockets library to implement WebSocket server and client in Python. The main concepts involved include:
WebSocket protocol foundation and its advantages;
How to implement WebSocket servers and clients;
How to handle exceptions, perform advanced applications such as message broadcasting and authentication.
The above is a detailed explanation of the examples of implementing WebSocket in Python. For more information about Python WebSocket, please follow my other related articles!