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.

106 satır
3.4KB

  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. from pprint import pprint
  17. import time
  18. abp.DETERMINISTIC = True
  19. clients = []
  20. local_state = abp.GraphState()
  21. def process_edit(edit, client, server):
  22. action = edit["action"]
  23. print action.upper()
  24. for key, value in edit.items():
  25. if key!="action":
  26. print " {}: {}".format(key, value)
  27. print
  28. if action == "create":
  29. local_state.add_qubit(edit["name"], position=edit["position"], vop=0)
  30. elif action == "cz":
  31. local_state.act_cz(edit["start"], edit["end"])
  32. elif action == "hadamard":
  33. local_state.act_hadamard(edit["node"])
  34. elif action == "phase":
  35. local_state.act_local_rotation(edit["node"], "phase")
  36. elif action == "delete":
  37. local_state._del_node(edit["node"])
  38. elif action == "localcomplementation":
  39. local_state.local_complementation(edit["node"])
  40. elif action == "measure":
  41. local_state.measure(edit["node"], "p"+edit["basis"])
  42. else:
  43. pass
  44. #server.send_message(client, json.dumps(local_state.to_json()))
  45. server.send_message_to_all(json.dumps(local_state.to_json()))
  46. def new_message(client, server, message):
  47. if message.startswith("edit:"):
  48. edit = json.loads(message[5:])
  49. process_edit(edit, client, server)
  50. else:
  51. print "Received update from python {}.".format(client["id"])
  52. # print message
  53. local_state.from_json(json.loads(message))
  54. # print local_state
  55. server.send_message_to_all(message)
  56. def new_client(client, server):
  57. print "Client {} connected.".format(client["id"])
  58. clients.append(client)
  59. print "Sent state of {} nodes to client {}".format(local_state.order(), client["id"])
  60. server.send_message(client, json.dumps(local_state.to_json()))
  61. def client_left(client, server):
  62. print "Client {} disconnected.".format(client["id"])
  63. clients.remove(client)
  64. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  65. """ Handle requests in a separate thread """
  66. if __name__ == '__main__':
  67. parser = argparse.ArgumentParser(description = "ABP websocket server")
  68. parser.add_argument("-v", action="store_true", help="Launch browser")
  69. args = parser.parse_args()
  70. # Change to the right working dir
  71. where = os.path.abspath(resource_filename("abp.static", ""))
  72. print "abpserver 0.4.23"
  73. print where
  74. print "Open http://localhost:5001 in a browser!"
  75. os.chdir(where)
  76. # Start the HTTP server
  77. httpserver = ThreadedHTTPServer(('', 5001), SimpleHTTPRequestHandler)
  78. thread = threading.Thread(target = httpserver.serve_forever)
  79. thread.daemon = True
  80. thread.start()
  81. if args.v:
  82. webbrowser.open("http://localhost:5001/")
  83. # Start the websocket server
  84. server = WebsocketServer(5000)
  85. server.set_fn_new_client(new_client)
  86. server.set_fn_message_received(new_message)
  87. server.set_fn_client_left(client_left)
  88. server.run_forever()
  89. httpserver.shutdown()