server.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. """
  2. A WebSocket server designed to relay audio data from a sender to a receiver
  3. in a remote microphone streaming system. It uses aiohttp to handle WebSocket
  4. connections. The server listens for incoming audio data on a specified port,
  5. authenticates clients based on a query parameter (password), and forwards audio
  6. data to all connected and authenticated receiver clients.
  7. Usage:
  8. Start the server by running this script with Python 3.x. It will listen for
  9. connections on 0.0.0.0 at the port defined at the bottom of the script.
  10. Senders and receivers connect to this server using the WebSocket protocol,
  11. allowing for real-time audio streaming from the sender to the receiver.
  12. """
  13. import asyncio
  14. from aiohttp import web
  15. # Set of connected WebSocket clients
  16. connected = set()
  17. # Your predefined password
  18. PASSWORD = "demopassword"
  19. async def websocket_handler(request):
  20. # Check password from query parameters
  21. if request.query.get("password") != PASSWORD:
  22. return web.Response(text="Unauthorized", status=401)
  23. ws = web.WebSocketResponse()
  24. await ws.prepare(request)
  25. print("A new client connected.")
  26. connected.add(ws)
  27. async for msg in ws:
  28. if msg.type == web.WSMsgType.TEXT:
  29. # Broadcast incoming text message to all connected websockets
  30. for socket in connected:
  31. if socket != ws:
  32. await socket.send_str(msg.data)
  33. elif msg.type == web.WSMsgType.BINARY:
  34. # Broadcast incoming binary message to all connected websockets
  35. for socket in connected:
  36. if socket != ws:
  37. try:
  38. await socket.send_bytes(msg.data)
  39. except Exception as e:
  40. pass
  41. elif msg.type == web.WSMsgType.ERROR:
  42. print("ws connection closed with exception %s" % ws.exception())
  43. print("Client disconnected.")
  44. connected.remove(ws)
  45. return ws
  46. async def init_app():
  47. app = web.Application()
  48. app.add_routes([web.get("/ws", websocket_handler)])
  49. return app
  50. loop = asyncio.get_event_loop()
  51. app = loop.run_until_complete(init_app())
  52. web.run_app(app, host="0.0.0.0", port=80) # Your host and port settings here