Anders and Briegel in Python
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

52 Zeilen
1.5KB

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