How can I send and receive WebSocket messages on the server side?

后端 未结 11 1895
轻奢々
轻奢々 2020-11-22 06:21
  • How can I send and receive messages on the server side using WebSocket, as per the protocol?

  • Why do I get seemingly random bytes at the server when

11条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:34

    pimvdb's answer implemented in python:

    def DecodedCharArrayFromByteStreamIn(stringStreamIn):
        #turn string values into opererable numeric byte values
        byteArray = [ord(character) for character in stringStreamIn]
        datalength = byteArray[1] & 127
        indexFirstMask = 2 
        if datalength == 126:
            indexFirstMask = 4
        elif datalength == 127:
            indexFirstMask = 10
        masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
        indexFirstDataByte = indexFirstMask + 4
        decodedChars = []
        i = indexFirstDataByte
        j = 0
        while i < len(byteArray):
            decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
            i += 1
            j += 1
        return decodedChars
    

    An Example of usage:

    fromclient = '\x81\x8c\xff\xb8\xbd\xbd\xb7\xdd\xd1\xd1\x90\x98\xea\xd2\x8d\xd4\xd9\x9c'
    # this looks like "?ŒOÇ¿¢gÓ ç\Ð=«ož" in unicode, received by server
    print DecodedCharArrayFromByteStreamIn(fromclient)
    # ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
    

提交回复
热议问题