简体   繁体   English

从Python中的WebSocket读取(Javascript WebSocket中的数据)

[英]Reading From a WebSocket in Python (Data from Javascript WebSocket)

I'm having some issues decoding data sent over websockets from Chrome (JavaScript) to a python server (using low-level socket apis). 我在解码通过websocket从Chrome(JavaScript)发送到python服务器(使用低级套接字api)的数据时遇到一些问题。 I've handled the handshake properly, the readyState of the websocket is OPEN when I use .send(...) . 我已经正确处理了握手,当我使用.send(...)时,websocket的readyState为OPEN。 I receive byte data (per the specs), but no matter how I try to decode it, it comes out as jibberish or triggers an exception. 我收到了字节数据(按照规范),但是无论我如何尝试对其进行解码,它都会以乱码的形式出现或触发异常。

javascript JavaScript的

var we = new WebSocket(url);
we.send("string data");

python 蟒蛇

data = socket.recv(1024) # socket from sock.accept(...)
#handle data

I've tried data.decode('utf-8') as that seems like it would be the obvious solution (throws an error). 我已经尝试过data.decode('utf-8')因为这似乎是显而易见的解决方案(引发错误)。 I've tried stripping \\x80 and \\x81 (I think - I read it somewhere on StackOverflow), but it still throws an error... 我试过剥离\\x80\\x81 (我认为-我在StackOverflow上的某个位置读取了它),但是仍然会抛出错误...

I've tried base64 decoding - which I found in an answer here on SO (but that doesn't make sense so...) 我已经尝试过base64解码-在SO上的一个答案中找到了它(但这没什么意义……)

Anything I'm missing? 我有什么想念的吗?

I'm not versed in WebSocket communication, but according to this answer , the data is encoded (see the part on Receiving Messages) 我不精通WebSocket通信,但是根据此答案 ,数据已编码(请参阅“接收消息”部分)

>>> pkt = [int(x, 16) for x in '81:85:86:56:99:b4:ee:33:f5:d8:e9'.split(':')]
>>> pkt[0] # header should be 129 for text mode
129
>>> len = pkt[1] & 0b01111111
>>> len
5
>>> mask = pkt[2:6]
>>> data = pkt[6:]
>>> for i,c in enumerate(data):
...     print chr(c ^ mask[i % 4])
...
h
e
l
l
o

Note, this is just an example of decoding your specific example data and does not take the full spec into account. 请注意,这只是解码特定示例数据的示例,并未考虑完整的规范。 For instance, the data length can be multiple bytes (so the position of the mask and data block may vary). 例如,数据长度可以是多个字节(因此掩码和数据块的位置可能会有所不同)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM