简体   繁体   中英

Python3 based WebSocket server, client closes connection on send

I'm learning python at the moment and choose a WebSocket server as a learning project, this might be not a wise decision after reading the WebSocket rfc...

The handshake and receiving single framed packages is working, but sending data back to client isn't. I'm using the Firefox and Chromium as clients for testing.

Both browsers are cancelling the connection when receiving data from the server, this is the Chromiums error message:

WebSocket connection to 'ws://localhost:1337/' failed: Unrecognized frame opcode: 13

The createFrame function should frame the message text, send to the client.

def createFrame (text):
    length = len(text)

    if length <= 125:
        ret = bytearray([129, length])

        for byte in text.encode("utf-8"):
            ret.append(byte)

        print(ret)

        return ret
#TODO 16 & 64Bit payload length

This is the createFrame debug output, which looks fine if I understood the rfc, the fin and utf8 bit are set, the 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 len(data) > 0:
    print(readFrame(data))
    conn.send(createFrame("Hello"))

The whole code can be found in this Gist: https://gist.github.com/Cacodaimon/33ff6c3c4b312b074c3e

You have an error on line 99 in your code. The error that 13 is not an opcode is coming from the fact that you generate a http response that looks like this:

HTTP/1.1 101 Switching Protocols\r\n
(...)\r\n
Sec-WebSocket-Accept: (...)==\n\r\n\r\n

Note the extra erroneous \\n, which is added by base64.encodestring . Apparently chrome interprets \\n\\r\\n as two correct newlines and the next token is \\r , which is 13: an incorrect opcode. When you replace base64.encodestring with base64.b64encode , the \\n is not added and your code works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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