Introduction
WebSocket is a communication protocol based on the TCP protocol, which enables full-duplex (two-way) communication between a client and a server. Compared with the traditional HTTP protocol, WebSocket can realize real-time data transmission, which is especially suitable for application scenarios that require real-time interaction, such as online games, real-time chat, financial transactions, etc.
I implement a simple WebSocket server through Python and make it communicate with the client. We will create two Python files:and
,
Responsible for implementing the functions of the WebSocket server,
Responsible for starting and managing the server, and sending messages to the client regularly.
Install the WebSocket library
Before you start, you need to install itwebsockets
library, it is a very popular WebSocket implementation in Python.
pip install websockets
— WebSocket Server Implementation
existIn the file, I defined a
WebSocketServer
Class, containing the main logic of the WebSocket server.
Code parsing
import asyncio import websockets class WebSocketServer: def __init__(self, host="localhost", port=8765): = host = port = set() # Store all connected clients
First, I created aWebSocketServer
class, its constructor initializes the server's host addresshost
and port numberport
, and maintain a client collection at the same time.clients
To store the currently connected WebSocket client.
async def handle_client(self, websocket): # New client connection (websocket) try: async for message in websocket: print(f"Received a message: {message}") # Echo the message to the client await (f"The server has been received: {message}") except as e: print(f"Client disconnection: {e}") finally: # Remove the disconnected client (websocket)
handle_client
is an asynchronous method used to handle connections to clients. When the client sends a message, the server will receive the message and pass()
Method sends an echo message to the client. If the client disconnects, captureConnectionClosed
Exception, and fromclients
Removes the client from the collection.
async def send(self, message): """Send messages to all connected clients""" if not : print("No client connection, no message sent") return disconnected_clients = set() for client in : try: await (message) except : disconnected_clients.add(client) # Clean up disconnected clients -= disconnected_clients
send
Method allows the server to send messages to all connected clients. If a client is disconnected, the server will remove it fromclients
Remove from the collection.
async def start(self): print(f"start up WebSocket server: ws://{}:{}") async with (self.handle_client, , ): await () # Continue to run until manually stop
start
Method starts the WebSocket server, through()
Start a WebSocket service that listens for connection requests from the client and callshandle_client
Methods handle these requests.await ()
The server will continue to run until it stops manually.
— Start the WebSocket server and send messages regularly
existIn the file, an instance of the WebSocket server is created and a timing task is initiated to send messages to the connected client periodically.
Code parsing
import asyncio from websocket import WebSocketServer async def main(): # Create a WebSocket server instance websocket_server = WebSocketServer() websocket_task = asyncio.create_task(websocket_server.start()) # Start the WebSocket server
existmain()
In the function, first createdWebSocketServer
instance and started the WebSocket server.
# Send data to WebSocket clients regularly async def send_data_periodically(): while True: await (5) # Send data every 5 seconds await websocket_server.send("Server sends messages regularly: ping")
send_data_periodically
It is a timed task that is sent to all connected clients every 5 seconds."Server sends messages regularly: ping"
。
periodic_task = asyncio.create_task(send_data_periodically()) # Run all tasks concurrently await (websocket_task, periodic_task)
passasyncio.create_task()
The timing task was started and passed()
The task of running the WebSocket server concurrently and sending messages regularly.
if __name__ == "__main__": (main())
Finally, we(main())
The entire program was started.
Summarize
Through these two files, a simple WebSocket server is implemented, which is able to receive client messages and echo them. At the same time, the server can also send messages to all connected clients regularly.
Complete code
import asyncio import websockets class WebSocketServer: def __init__(self, host="localhost", port=8765): = host = port = set() # Store all connected clients async def handle_client(self, websocket): # New client connection (websocket) try: async for message in websocket: print(f"Received a message: {message}") # Echo the message to the client await (f"The server has been received: {message}") except as e: print(f"Client disconnection: {e}") finally: # Remove the disconnected client (websocket) async def send(self, message): """Send messages to all connected clients""" if not : print("No client connection, no message sent") return disconnected_clients = set() for client in : try: await (message) except : disconnected_clients.add(client) # Clean up disconnected clients -= disconnected_clients async def start(self): print(f"start up WebSocket server: ws://{}:{}") async with (self.handle_client, , ): await () # Continue to run until manually stop
import asyncio from websocket import WebSocketServer async def main(): # Create a WebSocket server instance websocket_server = WebSocketServer() websocket_task = asyncio.create_task(websocket_server.start()) # Start the WebSocket server # Send data to WebSocket clients regularly async def send_data_periodically(): while True: await (5) # Send data every 5 seconds await websocket_server.send("Server sends messages regularly: ping") periodic_task = asyncio.create_task(send_data_periodically()) # Run all tasks concurrently await (websocket_task, periodic_task) if __name__ == "__main__": (main())
The above is the detailed content of using Python to implement communication between WebSocket server and client. For more information about Python WebSocket communication, please follow my other related articles!