Skip to content

How do I implement a broadcast server using picows? #35

@river-walras

Description

@river-walras

We assume a scenario where I have a server, and I need to broadcast the messages received to all clients, rather than having an echo server. How can this be achieved? I can implement a framework using WebSockets, but since picows creates a server that does not return transport, I cannot use transport to send messages.

import asyncio
from websockets.asyncio.server import serve

async def handler(websocket):
    ...

async def broadcast(message):
    ...

async def broadcast_messages():
    while True:
        await asyncio.sleep(1)
        message = ...  # your application logic goes here
        await broadcast(message)

async def main():
    async with serve(handler, "localhost", 8765):
        await broadcast_messages()  # runs forever

if __name__ == "__main__":
    asyncio.run(main())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions