python-websockets / websockets

Library for building WebSocket servers and clients in Python
https://websockets.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
5.16k stars 513 forks source link

Documentation: Hello-world example using threading instead of asyncio #1437

Closed josephernest closed 3 days ago

josephernest commented 8 months ago

This doc page gives a hello-world example: https://websockets.readthedocs.io/en/stable/index.html using the asyncio paradigm.

It supports several network I/O and control flow paradigms:

The default implementation builds upon asyncio, Python’s standard asynchronous I/O framework. It provides an elegant coroutine-based API. It’s ideal for servers that handle many clients concurrently.

The threading implementation is a good alternative for clients, especially if you aren’t familiar with asyncio. It may also be used for servers that don’t need to serve many clients. ...

Is there somewhere in the official documentation a hello-world simple server example using just threading, without asyncio?

Thanks!

aaugustin commented 8 months ago
#!/usr/bin/env python

from websockets.sync.server import serve

def hello(websocket):
    name = websocket.recv()
    print(f"< {name}")

    greeting = f"Hello {name}!"

    websocket.send(greeting)
    print(f"> {greeting}")

with serve(hello, "localhost", 8765) as server:
    server.serve_forever()