diff options
author | Pierre Ossman <pierre@ossman.eu> | 2016-09-15 19:51:26 +0200 |
---|---|---|
committer | Pierre Ossman <pierre@ossman.eu> | 2017-02-01 08:22:27 +0100 |
commit | 8a697622495fd319582cd1c604e7eb2cc0ac0ef6 (patch) | |
tree | 9270b1bb631c6559d2c0e9049a0d9b505b4c507c /tests/echo_client.py | |
parent | 4099949984eb80ef33c2d0dd216991124975a5d2 (diff) | |
download | websockify-8a697622495fd319582cd1c604e7eb2cc0ac0ef6.tar.gz |
Separate out raw WebSocket protocol handling
Diffstat (limited to 'tests/echo_client.py')
-rwxr-xr-x | tests/echo_client.py | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/tests/echo_client.py b/tests/echo_client.py new file mode 100755 index 0000000..6d745ec --- /dev/null +++ b/tests/echo_client.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python + +import os +import sys +import optparse +import select + +sys.path.insert(0,os.path.join(os.path.dirname(__file__), "..")) +from websockify.websocket import WebSocket, \ + WebSocketWantReadError, WebSocketWantWriteError + +parser = optparse.OptionParser(usage="%prog URL") +(opts, args) = parser.parse_args() + +try: + if len(args) != 1: raise + URL = args[0] +except: + parser.error("Invalid arguments") + +sock = WebSocket() +print("Connecting to %s..." % URL) +sock.connect(URL) +print("Connected.") + +def send(msg): + while True: + try: + sock.sendmsg(msg) + break + except WebSocketWantReadError: + msg = '' + ins, outs, excepts = select.select([sock], [], []) + if excepts: raise Exception("Socket exception") + except WebSocketWantWriteError: + msg = '' + ins, outs, excepts = select.select([], [sock], []) + if excepts: raise Exception("Socket exception") + +def read(): + while True: + try: + return sock.recvmsg() + except WebSocketWantReadError: + ins, outs, excepts = select.select([sock], [], []) + if excepts: raise Exception("Socket exception") + except WebSocketWantWriteError: + ins, outs, excepts = select.select([], [sock], []) + if excepts: raise Exception("Socket exception") + +counter = 1 +while True: + msg = "Message #%d" % counter + counter += 1 + send(msg) + print("Sent message: %r" % msg) + + while True: + ins, outs, excepts = select.select([sock], [], [], 1.0) + if excepts: raise Exception("Socket exception") + + if ins == []: + break + + while True: + msg = read() + print("Received message: %r" % msg) + + if not sock.pending(): + break |