python - Python3 based WebSocket server, client closes connection on send -
I am currently learning Python and choosing a websacet server as a learning project, this is probably an intelligent decision Reading WebSket RFCs is not ...
Getting hands-on and receiving single-framed packages is working, but the customer does not have to send the data back. I'm using Firefox and Chromium as clients for testing.
While retrieving data from the server, both browsers are canceling the connection, this is an error message from Chromium:
WebSket Connection 'ws: // localhost: 1337 / 'To fail: unrecognized frame opcode: 13
createFrame function should send a message text frame, Send to customer
def createFrame (text): Length = len (text) if length is & lt; = 125: ret = byteearray ([12 9, length]) for byte in text.encode ("utf-8"): Ret.append (byte) print (ret) return reserved #TODO 16 & amp; 64 bit payload length
This is the createframe debug output, which looks fine if I understand RFC, fin and UTF are 8 bits, length is 5:
bytearray (b '\ x81 \ x05Hello')
This is the primitive sending and receiving loop:
while 1: data = conn Recv (1024) #TODO multiple frames if lane (data) & gt; 0: print (readFrame (data)) conn.send (createFrame ("Hello"))
The entire code can be found in this code:
Your code has an error on line 99. Error 13 is not an opcode that is coming from the fact that you generate an HTTP response that looks like this:
HTTP / 1.1 101 Switching Protocol \ r \ n (.. .) \ R \ n Sec-WebSocket - Accept: (...) == \ n \ r \ n \ r \ n
Additional mistake \ n, which is Base64.encodestring
. Apparently, Chrome interprets \ n \ r \ n
as two correct new lines and the next token is \ r
, which is 13: one wrong opoad when If you change base64.encodestring
with base64.b64encode
, then \ n is not added and your code works as expected.
Comments
Post a Comment