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. clients = []
  11. def new_message(client, server, message):
  12. print "Received update from client {}.".format(client["id"])
  13. server.send_message_to_all(message)
  14. def new_client(client, server):
  15. print "Client {} connected.".format(client["id"])
  16. clients.append(client)
  17. def client_left(client, server):
  18. print "Client {} disconnected.".format(client["id"])
  19. clients.remove(client)
  20. class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
  21. """ Handle requests in a separate thread """
  22. if __name__ == '__main__':
  23. parser = argparse.ArgumentParser(description = "ABP websocket server")
  24. parser.add_argument("-v", action="store_false", help="Launch browser")
  25. args = parser.parse_args()
  26. # Change to the right working dir
  27. print abp.__path__
  28. where = os.path.join(os.path.dirname(abp.__path__[0]), "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()