From 68298dc3def66969a323b1f2eb35f598a96891e9 Mon Sep 17 00:00:00 2001 From: gregory80 Date: Thu, 9 Feb 2012 19:38:40 -0500 Subject: [PATCH] address issue #9 and other changes to the demo code --- examples/echoapp_client.py | 18 +++++++++++++----- websocket.py | 7 +++++-- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/examples/echoapp_client.py b/examples/echoapp_client.py index 3ea6a51..438e4b3 100644 --- a/examples/echoapp_client.py +++ b/examples/echoapp_client.py @@ -1,6 +1,7 @@ import websocket import thread import time +import sys def on_message(ws, message): print message @@ -14,20 +15,27 @@ def on_close(ws): def on_open(ws): def run(*args): for i in range(3): - time.sleep(1) + # send the message, then wait + # so thread doesnt exit and socket + # isnt closed ws.send("Hello %d" % i) + time.sleep(1) + time.sleep(1) ws.close() - print "thread terminating..." + print "Thread terminating..." + thread.start_new_thread(run, ()) - if __name__ == "__main__": websocket.enableTrace(True) - ws = websocket.WebSocketApp("ws://echo.websocket.org/", + if len(sys.argv) < 2: + host = "ws://echo.websocket.org/" + else: + host = sys.argv[1] + ws = websocket.WebSocketApp(host, on_message = on_message, on_error = on_error, on_close = on_close) ws.on_open = on_open - ws.run_forever() diff --git a/websocket.py b/websocket.py index dd4515f..b9353d9 100644 --- a/websocket.py +++ b/websocket.py @@ -55,7 +55,6 @@ STATUS_INVALID_EXTENSION = 1010 STATUS_UNEXPECTED_CONDITION = 1011 STATUS_TLS_HANDSHAKE_ERROR = 1015 - logger = logging.getLogger() class WebSocketException(Exception): @@ -515,7 +514,11 @@ class WebSocket(object): """ while True: frame = self.recv_frame() - if frame.opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): + if not frame: + # handle error: + # 'NoneType' object has no attribute 'opcode' + raise WebSocketException("Not a valid frame %s" % frame) + elif frame.opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): return (frame.opcode, frame.data) elif frame.opcode == ABNF.OPCODE_CLOSE: self.send_close()