python-websockets / websockets

Library for building WebSocket servers and clients in Python

Home Page:https://websockets.readthedocs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Documentation: Hello-world example using threading instead of asyncio

josephernest opened this issue · 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!

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