gpt4 book ai didi

java - 如何从 Python 中的套接字读取原始字节?

转载 作者:行者123 更新时间:2023-11-29 21:29:47 26 4
gpt4 key购买 nike

我有一个 android java 应用程序通过套接字发送字节,该套接字连接到在 Python 中运行服务器的主机。我需要接收这些字节,因为它们是从 python 套接字发送的。我看到在 Python 中 'socket.recv' 只返回一个字符串。当我从 java 应用程序发送 ASCII 字符串时,我能够在 python 服务器中正确接收数据,但是当我使用 java 字节发送二进制数据时,我看到接收到的数据不一样。我需要在 Python 中接收原始字节以使我的协议(protocol)正常工作。请指出正确的方向。

在套接字上发送数据的代码 fragment :

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代码

def recvFrameMessage(self, s):
recv_count = 4;
data = s.recv(recv_count)
if data == 0:
return None
total_rx = len(data)
lenInfo = data
while total_rx < recv_count:
data = s.recv(recv_count - total_rx)
if data == 0:
return None
total_rx += len(data)
lenInfo = lenInfo + data

recv_count = self.decodeFrameLen(lenInfo)
logger.info("length = %d" % recv_count)

data = s.recv(recv_count)
total_rx = len(data)
msg = data
while total_rx < recv_count:
data = s.recv(recv_count - total_rx)
if data == 0:
return None
total_rx += len(data)
msg = msg + data
logger.info("msg = " + msg)
for i in range(0, len(msg)-1):
logger.info("msg[%d] = %s" % (i, msg[i]))
return msg

最佳答案

@SteveP 对“具有某种结构”的二进制数据提出了很好的观点,但如果这是一个普通的字节流,在 Python 2 中只需将 ord() 函数应用于每个“字符”从套接字中获取。比如Java端发送一个NUL字节,在Python端会显示为字符"\x00",然后:

>>> ord("\x00")
0

要转换整个字符串s,

map(ord, s)

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

我在这里假设使用 Python 2。

关于java - 如何从 Python 中的套接字读取原始字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com