signaling-server.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env python
  2. #
  3. # Python signaling server example for libdatachannel
  4. # Copyright (c) 2020 Paul-Louis Ageneau
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. import sys
  19. import ssl
  20. import json
  21. import asyncio
  22. import logging
  23. import websockets
  24. logger = logging.getLogger('websockets')
  25. logger.setLevel(logging.INFO)
  26. logger.addHandler(logging.StreamHandler(sys.stdout))
  27. clients = {}
  28. async def handle_websocket(websocket, path):
  29. client_id = None
  30. try:
  31. splitted = path.split('/')
  32. splitted.pop(0)
  33. client_id = splitted.pop(0)
  34. print('Client {} connected'.format(client_id))
  35. clients[client_id] = websocket
  36. while True:
  37. data = await websocket.recv()
  38. print('Client {} << {}'.format(client_id, data))
  39. message = json.loads(data)
  40. destination_id = message['id']
  41. destination_websocket = clients.get(destination_id)
  42. if destination_websocket:
  43. message['id'] = client_id
  44. data = json.dumps(message)
  45. print('Client {} >> {}'.format(destination_id, data))
  46. await destination_websocket.send(data)
  47. else:
  48. print('Client {} not found'.format(destination_id))
  49. except Exception as e:
  50. print(e)
  51. finally:
  52. if client_id:
  53. del clients[client_id]
  54. print('Client {} disconnected'.format(client_id))
  55. if __name__ == '__main__':
  56. # Usage: ./server.py [[host:]port] [SSL certificate file]
  57. endpoint_or_port = sys.argv[1] if len(sys.argv) > 1 else "8000"
  58. ssl_cert = sys.argv[2] if len(sys.argv) > 2 else None
  59. endpoint = endpoint_or_port if ':' in endpoint_or_port else "127.0.0.1:" + endpoint_or_port
  60. if ssl_cert:
  61. ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
  62. ssl_context.load_cert_chain(ssl_cert)
  63. else:
  64. ssl_context = None
  65. print('Listening on {}'.format(endpoint))
  66. host, port = endpoint.rsplit(':', 1)
  67. start_server = websockets.serve(handle_websocket, host, int(port), ssl=ssl_context)
  68. asyncio.get_event_loop().run_until_complete(start_server)
  69. asyncio.get_event_loop().run_forever()