1. Introduction to WebSocket
WebSocket is a TCP-based protocol that supports full-duplex communication (the server and client can send messages at the same time), and is suitable for scenarios with high real-time requirements (such as chat, real-time data monitoring, online games, etc.). Unlike HTTP, WebSocket connections are persisted once established, avoiding the overhead of HTTP polling.
2. Python’s websockets library
websockets
It is an asynchronous library used in Python to build WebSocket servers and clients, based onasyncio
Implemented, supporting high concurrency and low latency communication.
Install
pip install websockets
3. Complete code example
1. WebSocket Server
import asyncio import websockets from datetime import datetime # Save all active client connectionsconnected_clients = set() async def handle_client(websocket, path): """ Handle a single client connection """ # Add a new client to the collection connected_clients.add(websocket) try: async for message in websocket: # Broadcast messages to all clients timestamp = ().strftime("%H:%M:%S") broadcast_message = f"[{timestamp}] {message}" await broadcast(broadcast_message) except : print("Client disconnection") finally: # Remove after the client is disconnected connected_clients.remove(websocket) async def broadcast(message): """ Broadcast messages to all connected clients """ if connected_clients: await ( *[(message) for client in connected_clients] ) async def start_server(): """ Start the WebSocket Server """ async with (handle_client, "localhost", 8765): print("The server has been started, listening port 8765...") await () # Permanently run if __name__ == "__main__": (start_server())
2. WebSocket Client
import asyncio import websockets async def client(): """ WebSocket Client Implementation """ async with ("ws://localhost:8765") as websocket: # Create two tasks: one receives messages and one sends messages receive_task = asyncio.create_task(receive_messages(websocket)) send_task = asyncio.create_task(send_messages(websocket)) await (receive_task, send_task) async def receive_messages(websocket): """ Receive server messages """ async for message in websocket: print(f"\nReceived a message: {message}") async def send_messages(websocket): """ Send a message entered by the user """ while True: message = await asyncio.get_event_loop().run_in_executor(None, input, "Enter a message (enter 'exit' quit): ") if ().lower() == 'exit': break await (message) if __name__ == "__main__": (client())
4. Detailed explanation of the code
Server side
-
connected_clients
: Use collection to save all active connections for easy broadcasting. -
handle_client
:- Accept new connections and add to the collection.
- Receive client messages in a loop and call them after receiving them
broadcast
Broadcast. - Handle the connection disconnection exception and ensure that the client is removed.
-
broadcast
:useSend messages concurrently to all clients.
-
start_server
: Start the server and run it permanently.
Client
-
client
: Connect to the server and start the sending and receiving task. -
receive_messages
: Receive server messages cycled and print them. -
send_messages
: Read user input and send to the server (run_in_executor
Used for asynchronous processing of blockinginput
)。
V. Operation and testing
- Start the server:
python
- Start multiple clients:
python
- test: Enter a message on either client and all clients will receive a broadcast.
6. Advanced usage
-
Message Agreement: You can define JSON format messages and add type fields (such as
{"type": "chat", "content": "Hello"}
)。 -
Certification: Verify the token on connection (pass
path
Parameters or first handshake message). - Heartbeat mechanism: Send regularly Ping/Pong to keep the connection active.
- Integrate FastAPI: Provides HTTP + WebSocket hybrid services in conjunction with the ASGI framework.
7. Application scenarios
- Live chat application
- Multiplayer online game
- Stock market push
- Internet of Things Device Monitoring
8. Summary
passwebsockets
Library, which can easily build high-performance real-time applications. The code examples provided in this article cover the basic implementation of servers and clients, with detailed comments and can be directly extended for actual projects.
This is the article about the use guide of the Python Websockets library. For more information about the use of the Python Websockets library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!