我目前正在处理客户端-服务器连接。
客户端使用 Java 编写,而不使用在Android手机上运行的QT,服务器使用C++使用 Qt框架编写。
客户端收到QByteArrays , QStrings 和 QLists ,但是我不知道如何反序列化和解释传入的数据。
创建必须在Java客户端读取的数据包的C++源代码如下所示:
QByteArray body;
QString string1, string2, string3;
QList<float> list;
qint8 recognitionCount;
QDataStream bodyStream(&body, QIODevice::WriteOnly);
bodyStream << recognitionCount;
bodyStream << string1.toUtf8()
<< string2.toUtf8()
<< string3.toUtf8()
<< list;
客户端和服务器之间的连接已建立并且运行良好。我了解例如如何读取服务器发送给我的整数。我也知道如何读取字节,但是我应该如何处理这些字节?例如,如何将它们格式化为字符串?
谁能帮我吗?
我真的很感谢您的帮助!
最佳答案
您可以像这样(根据this definition)将Qt字符串转换为Java:
final static int MAX_STRING_LENGTH = 10240; // arbitrary number
private final static ByteBuffer stringBytes = ByteBuffer.allocate(MAX_STRING_LENGTH);
static String readStringFromQTStream(final ObjectInputStream in) throws IOException {
if (in.available() < (Integer.SIZE / 8)) { // check that there are at least 4 bytes for the length
throw new IOException("Illegal data received: expected integer but only got " + in.available() + " bytes");
}
final int stringLength = in.readInt();
if (stringLength == 0xFFFFFFFF) { // Qt for null string
return null;
}
if ((stringLength < 0) || (stringLength > stringBytes.capacity())) { // check for malformed data
throw new IOException("Illegal data received: string with supposed length of " + stringLength + " bytes");
}
stringBytes.clear(); // global var, not thread-safe!
in.readFully(stringBytes.array(), 0, stringLength);
stringBytes.flip();
return StandardCharsets.UTF_8.decode(stringBytes).toString();
}
请注意,ByteBuffer被重用,如果您经常读取数据,这可以提高性能,但是如果没有更多代码,这当然不是线程安全的。