Anders and Briegel in Python
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

60 satır
1.8KB

  1. #!/usr/bin/python
  2. """
  3. This is a simple websocket relay server that facilitates realtime visualization of GraphStates.
  4. It doesn't do much except echo websocket messages to all connected clients, and serve some static content over HTTP.
  5. """
  6. from websocket_server import WebsocketServer
  7. from SimpleHTTPServer import SimpleHTTPRequestHandler
  8. from BaseHTTPServer import HTTPServer
  9. from SocketServer import ThreadingMixIn
  10. import os, sys, threading
  11. import webbrowser
  12. import argparse
  13. import abp
  14. from pkg_resources import resource_filename
  15. clients = []
  16. def new_message(client, server, message):
  17. print "Received update from client {}.".format(client["id"])
  18. server.send_message_to_all(message)
  19. def new_client(client, server):
  20. print "Client {} connected.".format(client["id"])
  21. clients.append(client)
  22. def client_left(client, server):
  23. print "Client {} disconnected.".format(client["id"])
  24. clients.remove(client)
  25. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  26. """ Handle requests in a separate thread """
  27. if __name__ == '__main__':
  28. parser = argparse.ArgumentParser(description = "ABP websocket server")
  29. parser.add_argument("-v", action="store_true", help="Launch browser")
  30. args = parser.parse_args()
  31. # Change to the right working dir
  32. where = os.path.abspath(resource_filename("abp.static", ""))
  33. os.chdir(where)
  34. # Start the HTTP server
  35. httpserver = ThreadedHTTPServer(('', 5001), SimpleHTTPRequestHandler)
  36. thread = threading.Thread(target = httpserver.serve_forever)
  37. thread.daemon = True
  38. thread.start()
  39. if args.v:
  40. webbrowser.open("http://localhost:5001/")
  41. # Start the websocket server
  42. server = WebsocketServer(5000)
  43. server.set_fn_new_client(new_client)
  44. server.set_fn_message_received(new_message)
  45. server.set_fn_client_left(client_left)
  46. server.run_forever()
  47. httpserver.shutdown()