Anders and Briegel in Python
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

server.py 1.6KB

8年前
8年前
8年前
8年前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import urlparse
  2. from BaseHTTPServer import BaseHTTPRequestHandler
  3. from SimpleHTTPServer import SimpleHTTPRequestHandler
  4. import SocketServer
  5. import sys
  6. import json
  7. import threading
  8. import time
  9. class VizHandler(SimpleHTTPRequestHandler):
  10. """ Handles requests to the server """
  11. def __init__(self, *args, **kwargs):
  12. SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
  13. def get_state(self):
  14. self.send_response(200)
  15. self.send_header('Content-Type', 'application/json')
  16. self.end_headers()
  17. self.wfile.write(json.dumps({"state":"here is the state"}))
  18. def do_GET(self, *args, **kwargs):
  19. parsed_path = urlparse.urlparse(self.path)
  20. print parsed_path.path
  21. if parsed_path.path == "/state":
  22. return self.get_state()
  23. else:
  24. return SimpleHTTPRequestHandler.do_GET(self, *args, **kwargs)
  25. class VizServer(SocketServer.TCPServer):
  26. """ Runs the server in a new thread """
  27. allow_reuse_address = True
  28. def __init__(self, port = 8000):
  29. self.port = port
  30. SocketServer.TCPServer.__init__(self, ("127.0.0.1", self.port), VizHandler)
  31. def run(self):
  32. try:
  33. self.serve_forever()
  34. except KeyboardInterrupt:
  35. "Caught keyboard interrupt"
  36. self.shutdown()
  37. def start(self):
  38. thread = threading.Thread(None, self.run)
  39. thread.daemon = True
  40. thread.start()
  41. print "Go to 127.0.0.0:{}".format(self.port)
  42. if __name__ == '__main__':
  43. server = VizServer()
  44. server.start()
  45. time.sleep(5)
  46. server.shutdown()