如何从Python套接字读取原始字节?

2024-09-30 18:14:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个android java应用程序通过一个套接字发送字节,这个套接字连接到运行Python服务器的主机上。我需要接收从python套接字发送的这些字节。我在Python中看到了接收插座'只返回字符串。当我从java应用程序发送一个ASCII字符串时,我能够在python服务器中正确地接收数据,但是当我使用java字节发送二进制数据时,我看到接收到的数据是不一样的。我需要接收Python中的原始字节才能使我的协议正常工作。请给我指一下正确的方向。在

用于在套接字上发送数据的代码段:

private void sendFrameMessage(byte[] data) {
        byte[] lengthInfo = new byte[4];
        Log.v(TAG, "sendFrameMessage");

        for(int i=0; i<data.length; i++) {
            Log.v(TAG, String.format("data[%d] = %d", i, data[i]));
        }

        try {
            lengthInfo[0] = (byte) data.length;
            lengthInfo[1] = (byte) (data.length >> 8);
            lengthInfo[2] = (byte) (data.length >> 16);
            lengthInfo[3] = (byte) (data.length >> 24);
            DataOutputStream dos;
            dos = new DataOutputStream(mSocket.getOutputStream());
            dos.write(lengthInfo, 0, 4);
            dos.write(data, 0, data.length);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

接收端的Python代码

^{pr2}$

Tags: 数据字符串服务器log应用程序newdata字节
2条回答

读取二进制数据是完全可行的,但是如果android应用程序的二进制表示与Python服务器上的字节表示不同呢?从Python文档中:

It is perfectly possible to send binary data over a socket. The major problem is that not all machines use the same formats for binary data. For example, a Motorola chip will represent a 16 bit integer with the value 1 as the two hex bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00. Socket libraries have calls for converting 16 and 32 bit integers - ntohl, htonl, ntohs, htons where “n” means network and “h” means host, “s” means short and “l” means long. Where network order is host order, these do nothing, but where the machine is byte-reversed, these swap the bytes around appropriately.

如果没有代码和示例输入/输出,这个问题将很难回答。我想问题是代表性不同。最有可能的问题是Java使用big-endian,而Python遵循任何运行它的机器。如果您的服务器使用little-endian,那么您需要对此进行解释。有关endianness的更详细的解释,请参阅此处。在

@stevp对二进制数据“具有某种结构”做了很好的说明,但是如果这是一个普通的字节流,那么在python2中,只需将ord()函数应用于从套接字获得的每个“字符”。例如,如果Java端发送一个NUL字节,则在Python端将显示为字符"\x00",然后:

>>> ord("\x00")
0

要转换整个字符串s

^{pr2}$

返回对应的8位无符号整数的列表。在

我假设这里是Python2。在

相关问题 更多 >