echo_client.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #!/usr/bin/env python
  2. import os
  3. import sys
  4. import optparse
  5. import select
  6. sys.path.insert(0,os.path.join(os.path.dirname(__file__), ".."))
  7. from websockify.websocket import WebSocket, \
  8. WebSocketWantReadError, WebSocketWantWriteError
  9. parser = optparse.OptionParser(usage="%prog URL")
  10. (opts, args) = parser.parse_args()
  11. if len(args) == 1:
  12. URL = args[0]
  13. else:
  14. parser.error("Invalid arguments")
  15. sock = WebSocket()
  16. print("Connecting to %s..." % URL)
  17. sock.connect(URL)
  18. print("Connected.")
  19. def send(msg):
  20. while True:
  21. try:
  22. sock.sendmsg(msg)
  23. break
  24. except WebSocketWantReadError:
  25. msg = ''
  26. ins, outs, excepts = select.select([sock], [], [])
  27. if excepts: raise Exception("Socket exception")
  28. except WebSocketWantWriteError:
  29. msg = ''
  30. ins, outs, excepts = select.select([], [sock], [])
  31. if excepts: raise Exception("Socket exception")
  32. def read():
  33. while True:
  34. try:
  35. return sock.recvmsg()
  36. except WebSocketWantReadError:
  37. ins, outs, excepts = select.select([sock], [], [])
  38. if excepts: raise Exception("Socket exception")
  39. except WebSocketWantWriteError:
  40. ins, outs, excepts = select.select([], [sock], [])
  41. if excepts: raise Exception("Socket exception")
  42. counter = 1
  43. while True:
  44. msg = "Message #%d" % counter
  45. counter += 1
  46. send(msg)
  47. print("Sent message: %r" % msg)
  48. while True:
  49. ins, outs, excepts = select.select([sock], [], [], 1.0)
  50. if excepts: raise Exception("Socket exception")
  51. if ins == []:
  52. break
  53. while True:
  54. msg = read()
  55. print("Received message: %r" % msg)
  56. if not sock.pending():
  57. break