client.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. from getpass import getpass
  2. import websocket
  3. import _thread
  4. import json
  5. from cmd import Cmd
  6. class MyPrompt(Cmd):
  7. def __init__(self, ws):
  8. super(MyPrompt, self).__init__()
  9. self.ws = ws
  10. def do_build(self, args):
  11. """Starts the construction of a building."""
  12. send_json(self.ws, {
  13. 'type': "build",
  14. 'building': args,
  15. })
  16. def do_exit(self, args):
  17. """Exits the program."""
  18. print("Exiting.")
  19. raise SystemExit
  20. def default(self, line):
  21. print("Unknown command: " + line)
  22. def emptyline(self):
  23. pass
  24. def send_json(ws, message):
  25. ws.send(json.dumps(message))
  26. def on_message(ws, message):
  27. print(message)
  28. def on_error(ws, error):
  29. print(error)
  30. def on_close(ws):
  31. print("### closed ###")
  32. def on_open(username, password, register=False):
  33. def run(ws):
  34. send_json(ws, {
  35. 'type': "register" if register else "login",
  36. 'username': username,
  37. 'password': password,
  38. })
  39. return run
  40. def main():
  41. ws = websocket.WebSocketApp("ws://localhost:6060",
  42. on_message = on_message,
  43. on_error = on_error,
  44. on_close = on_close)
  45. option = 0
  46. while option not in (1, 2):
  47. print("1. Login")
  48. print("2. Register")
  49. print("> ", end="", flush=True)
  50. option = int(input())
  51. print("Username: ", end="", flush=True)
  52. username = input()
  53. password = getpass()
  54. ws.on_open = on_open(username, password, option == 2)
  55. def run(*args):
  56. ws.run_forever()
  57. _thread.start_new_thread(run, ())
  58. prompt = MyPrompt(ws)
  59. prompt.prompt = '> '
  60. prompt.cmdloop('Starting prompt...')
  61. if __name__ == "__main__":
  62. main()