Anders and Briegel in Python
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abpserver 2.1KB

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