简体   繁体   English

将字节数组向后移植到 Python 2.5

[英]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.我正在尝试将此websocket 示例转换为在 Python 2.5 中使用,但在使用 bytearray 类型时遇到了错误。

The code stops working for Python 2.5 here (in the send_text method of websocket_server/websocket_server.py ):代码在此处停止适用于 Python 2.5(在websocket_server/websocket_server.py的 send_text 方法中):

    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. message 变量存储发送给客户端的字符串输入。

It attempts to create an array of bytes and send that using the self.request.send method.它尝试创建一个字节数组并使用 self.request.send 方法发送它。 How would I change this to make it work in Python 2.5 which doesn't have the bytes type or bytearray?我将如何更改它以使其在没有字节类型或字节数组的 Python 2.5 中工作?

Using struct MIGHT work, I haven't tested this.使用 struct 可能有效,我还没有测试过。

What I would do, as a workaround, would be to use struct.pack to pack byte by byte.作为一种解决方法,我会做的是使用 struct.pack 逐字节打包。

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).我在 struct.pack 函数中使用“H”作为“fmt”参数,但你最好检查你的包是如何发送的以及每个“字符”有多少字节(因为我猜你正在使用 unicode,我'正在使用'H',无符号短 = 2 个字节)。

More info: https://docs.python.org/2/library/struct.html , section 7.3.2.1 and 7.3.2.2.更多信息: https ://docs.python.org/2/library/struct.html,第 7.3.2.1 和 7.3.2.2 节。

EDIT: I'll answer here, what do I mean by using 'chr()' instead of 'struct.pack()':编辑:我会在这里回答,使用“chr()”而不是“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).如果您打印的消息,那么您在使用时会看到相同的输出struct.pack("B", ord(something))使用时,比ord(something) ,我只是用struct.pack(),因为我认为你的信息是每个字符两个字节(作为 unicode)。

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

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