From 382707436f863443219a4adf5461f393f93e7503 Mon Sep 17 00:00:00 2001 From: Sergei Maertens Date: Wed, 14 Aug 2019 11:00:17 +0200 Subject: [PATCH] Refs. #151 -- detect binary payloads and send the correct opcode On Python 2, strings are bytestrings either way. On Python 3, the result of `chr(channel)` is `str`, while the data itself is `bytes`. The channel prefix needs to be turned into a binary type, and the websocket frame needs the correct opcode (binary vs. text). See #151 for the bug report and related issues. --- stream/ws_client.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/stream/ws_client.py b/stream/ws_client.py index a1a96f2d..590bd8d7 100644 --- a/stream/ws_client.py +++ b/stream/ws_client.py @@ -116,7 +116,16 @@ def readline_channel(self, channel, timeout=None): def write_channel(self, channel, data): """Write data to a channel.""" - self.sock.send(chr(channel) + data) + # check if we're writing binary data or not + binary = six.PY3 and type(data) == six.binary_type + opcode = ABNF.OPCODE_BINARY if binary else ABNF.OPCODE_TEXT + + channel_prefix = chr(channel) + if binary: + channel_prefix = six.binary_type(channel_prefix, "ascii") + + payload = channel_prefix + data + self.sock.send(payload, opcode=opcode) def peek_stdout(self, timeout=0): """Same as peek_channel with channel=1."""