Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514-thinking-16k· AnthropicHugging Face LMArena Human Preference 140K

how to create websocket in python

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Amazon Novaamazon.nova-pro-v1:0’s answer.
  1. User

    how to create websocket in python

  2. Claude Assistant

    To create WebSockets in Python, you'll typically use the websockets library, 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 websockets library uses Python's asyncio for asynchronous operations, which makes it efficient for handling multiple concurrent connections. The key concepts are that the server uses websockets.serve() to listen for connections, while clients use websockets.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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.