简体   繁体   中英

Backporting bytearray to Python 2.5

I'm trying to convert this websocket example for use in Python 2.5, but am running into errors with the use of the bytearray type.

The code stops working for Python 2.5 here (in the send_text method of websocket_server/websocket_server.py ):

    FIN    = 0x80
    OPCODE = 0x0f
    def send_text(self, message):
       header = bytearray();
       payload = encode_to_UTF8(message)
       payload_length = len(payload)
       header.append(FIN | OPCODE_TEXT)
       header.append(payload_length)

       self.request.send(header + payload)

The message variable stores the string input that is sent to clients.

It attempts to create an array of bytes and send that using the self.request.send method. How would I change this to make it work in Python 2.5 which doesn't have the bytes type or bytearray?

Using struct MIGHT work, I haven't tested this.

What I would do, as a workaround, would be to use struct.pack to pack byte by byte.

mensaje = "saludo"
FIN    = 0x80
OPCODE = 0x0f
payload = ''
for c in mensaje:
    payload += struct.pack("H", ord(c))

msj = struct.pack("H",FIN | OPCODE )
msj+= struct.pack("H",len(payload))
print msj + payload

I'm using "H" as the 'fmt' parameter in the struct.pack function, but you better check how is your package sent and how many bytes per 'character' (since I'm guessing you're using unicode, I'm using 'H', unsigned short = 2 bytes).

More info: https://docs.python.org/2/library/struct.html , section 7.3.2.1 and 7.3.2.2.

EDIT: I'll answer here, what do I mean by using 'chr()' instead of 'struct.pack()':

mensaje = "saludo"
FIN    = 0x80
OPCODE = 0x0f
payload = mensaje
msj = chr( FIN | OPCODE )
msj+= chr(len(payload))
print msj + payload

if you print the message, then you should see the same output when using struct.pack("B", ord(something)) than when using ord(something) , I just used struct.pack() because I thought your message was two bytes per char (as unicode).

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