Anders and Briegel in Python
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

71 строка
2.2KB

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