Anders and Briegel in Python
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

88 líneas
2.6KB

  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. import json
  15. from pkg_resources import resource_filename
  16. clients = []
  17. local_state = abp.GraphState()
  18. def process_edit(edit, server):
  19. action = edit["action"]
  20. print edit
  21. print local_state.node.keys()
  22. if action == "create":
  23. print type(edit["name"])
  24. local_state.add_qubit(edit["name"], position=edit["position"], vop=0)
  25. if action == "cz":
  26. local_state.act_cz(edit["start"], edit["end"])
  27. server.send_message_to_all(json.dumps(local_state.to_json()))
  28. def new_message(client, server, message):
  29. if message.startswith("edit:"):
  30. print message[5:]
  31. edit = json.loads(message[5:])
  32. print "Received update from javascript."
  33. process_edit(edit, server)
  34. else:
  35. print "Received update from python {}.".format(client["id"])
  36. print message
  37. local_state.from_json(json.loads(message))
  38. print local_state
  39. server.send_message_to_all(message)
  40. def new_client(client, server):
  41. print "Client {} connected.".format(client["id"])
  42. clients.append(client)
  43. def client_left(client, server):
  44. print "Client {} disconnected.".format(client["id"])
  45. clients.remove(client)
  46. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  47. """ Handle requests in a separate thread """
  48. if __name__ == '__main__':
  49. parser = argparse.ArgumentParser(description = "ABP websocket server")
  50. parser.add_argument("-v", action="store_true", help="Launch browser")
  51. args = parser.parse_args()
  52. # Change to the right working dir
  53. where = os.path.abspath(resource_filename("abp.static", ""))
  54. os.chdir(where)
  55. # Start the HTTP server
  56. httpserver = ThreadedHTTPServer(('', 5001), SimpleHTTPRequestHandler)
  57. thread = threading.Thread(target = httpserver.serve_forever)
  58. thread.daemon = True
  59. thread.start()
  60. if args.v:
  61. webbrowser.open("http://localhost:5001/")
  62. # Start the websocket server
  63. server = WebsocketServer(5000)
  64. server.set_fn_new_client(new_client)
  65. server.set_fn_message_received(new_message)
  66. server.set_fn_client_left(client_left)
  67. server.run_forever()
  68. httpserver.shutdown()