Anders and Briegel in Python
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

56 lines
1.6KB

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