我有一个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}$
读取二进制数据是完全可行的,但是如果android应用程序的二进制表示与Python服务器上的字节表示不同呢?从Python文档中:
如果没有代码和示例输入/输出,这个问题将很难回答。我想问题是代表性不同。最有可能的问题是Java使用big-endian,而Python遵循任何运行它的机器。如果您的服务器使用little-endian,那么您需要对此进行解释。有关endianness的更详细的解释,请参阅此处。在
@stevp对二进制数据“具有某种结构”做了很好的说明,但是如果这是一个普通的字节流,那么在python2中,只需将
ord()
函数应用于从套接字获得的每个“字符”。例如,如果Java端发送一个NUL字节,则在Python端将显示为字符"\x00"
,然后:要转换整个字符串
^{pr2}$s
返回对应的8位无符号整数的列表。在
我假设这里是Python2。在
相关问题 更多 >
编程相关推荐