websockets icon indicating copy to clipboard operation
websockets copied to clipboard

Documentation: Hello-world example using threading instead of asyncio

Open josephernest opened this issue 1 year ago • 1 comments

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!

josephernest avatar Jan 30 '24 14:01 josephernest

#!/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()

aaugustin avatar Jan 30 '24 22:01 aaugustin