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())
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.