how to create websocket in python
- User
how to create websocket in python
Assistant
To create WebSockets in Python, you'll typically use the
websocketslibrary, which provides a clean and straightforward implementation. First, install it using pip:pip install websockets.Here's how to create a WebSocket server:
import asyncio import websockets async def handle_client(websocket, path): try: # Wait for messages from the client async for message in websocket: print(f"Received: {message}") # Echo the message back to the client await websocket.send(f"Echo: {message}") except websockets.exceptions.ConnectionClosed: print("Client disconnected") async def main(): # Start the server on localhost:8765 async with websockets.serve(handle_client, "localhost", 8765): print("WebSocket server started on ws://localhost:8765") await asyncio.Future() # Run forever if __name__ == "__main__": asyncio.run(main())And here's a WebSocket client to connect to the server:
import asyncio import websockets async def client(): uri = "ws://localhost:8765" async with websockets.connect(uri) as websocket: # Send messages to the server await websocket.send("Hello, server!") response = await websocket.recv() print(f"Server response: {response}") # Send another message await websocket.send("How are you?") response = await websocket.recv() print(f"Server response: {response}") if __name__ == "__main__": asyncio.run(client())For more advanced use cases, you might want to handle multiple clients, broadcast messages, or implement authentication. Here's an example of a server that broadcasts messages to all connected clients:
import asyncio import websockets import json # Keep track of all connected clients connected_clients = set() async def handle_client(websocket, path): # Register new client connected_clients.add(websocket) try: async for message in websocket: # Broadcast message to all connected clients if connected_clients: await asyncio.gather( *[client.send(message) for client in connected_clients] ) finally: # Remove client when they disconnect connected_clients.remove(websocket) async def main(): async with websockets.serve(handle_client, "localhost", 8765): print("Broadcasting WebSocket server started") await asyncio.Future() if __name__ == "__main__": asyncio.run(main())The
websocketslibrary uses Python's asyncio for asynchronous operations, which makes it efficient for handling multiple concurrent connections. The key concepts are that the server useswebsockets.serve()to listen for connections, while clients usewebsockets.connect()to establish connections. Both operations are asynchronous and should be used within async functions.For web applications, you might also consider using WebSocket support in frameworks like FastAPI, Django Channels, or Flask-SocketIO, which provide additional features and integrate well with existing web applications.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.