Skip to content

Commit 3fcb166

Browse files
committed
fixed closing frame support
1 parent 8da37c1 commit 3fcb166

3 files changed

Lines changed: 26 additions & 8 deletions

File tree

ws4py/messaging.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# -*- coding: utf-8 -*-
22
import os
3+
import struct
34

45
from ws4py.framing import Frame, OPCODE_CONTINUATION, OPCODE_TEXT, \
56
OPCODE_BINARY, OPCODE_CLOSE, OPCODE_PING, OPCODE_PONG
@@ -115,7 +116,13 @@ def is_text(self):
115116

116117
class CloseControlMessage(Message):
117118
def __init__(self, code=1000, reason=''):
118-
Message.__init__(self, OPCODE_CLOSE, reason)
119+
data = ""
120+
if code:
121+
data += struct.pack("!H", code)
122+
if reason:
123+
data += reason.encode('utf-8')
124+
125+
Message.__init__(self, OPCODE_CLOSE, data)
119126
self.code = code
120127
self.reason = reason
121128

ws4py/server/handler/threadedhandler.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -215,17 +215,19 @@ def _receive(self):
215215
for pong in s.pongs:
216216
self.ponged(pong)
217217
s.pongs = []
218-
219218
except:
220219
print "".join(traceback.format_exception(*exc_info()))
221220
finally:
222221
self.client_terminated = self.server_terminated = True
223-
self.close_connection()
224-
if self.stream.closing:
225-
self.closed(self.stream.closing.code, self.stream.closing.reason)
226-
else:
227-
self.closed(1006)
228222

223+
try:
224+
if not self.server_terminated:
225+
if self.stream.closing:
226+
self.closed(self.stream.closing.code, self.stream.closing.reason)
227+
else:
228+
self.closed(1006)
229+
finally:
230+
self.close_connection()
229231

230232
class EchoWebSocketHandler(WebSocketHandler):
231233
"""

ws4py/streaming.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
import struct
3+
24
from ws4py.messaging import TextMessage, BinaryMessage, CloseControlMessage,\
35
PingControlMessage, PongControlMessage
46
from ws4py.framing import Frame, OPCODE_CONTINUATION, OPCODE_TEXT, \
@@ -203,7 +205,14 @@ def receiver(self):
203205
m.extend(bytes)
204206

205207
elif frame.opcode == OPCODE_CLOSE:
206-
self.closing = CloseControlMessage(reason=bytes.decode("utf-8", "replace"))
208+
code = 1000
209+
reason = ""
210+
bytes = str(bytes)
211+
if len(bytes) > 1:
212+
code = struct.unpack("!H", bytes[0:2])[0]
213+
if len(bytes) > 2:
214+
reason = bytes[2:].decode("utf-8", "replace")
215+
self.closing = CloseControlMessage(code=code, reason=reason)
207216

208217
elif frame.opcode == OPCODE_PING:
209218
self.pings.append(PingControlMessage(bytes))

0 commit comments

Comments
 (0)