我有以下原型文件
package DS3DExcite.Cpp.ExternalVariantSwitcher.ProtocolBuffers;
message DGCommand
{
extensions 100 to max;
enum Type
{
AttachModel = 1;
AttachModelReply = 2;
....
...
SwitchVariants = 4;
}
required Type type = 1;
required uint32 id = 2;
optional uint32 replyTo = 3 [default = 0];
optional string message = 4;
}
message SwitchVariants
{
extend DGCommand
{
required SwitchVariants command = 103;
}
message VariantState
{
required string variant = 1;
required string state = 2;
}
repeated VariantState variants = 1;
repeated string variantNames = 2;
optional string state = 3;
}
我使用protobuf 2.4.1版本编译了原型文件,以生成.pb.h和.pb.cc文件
现在我形成了命令
DS3DExcite::Net::PVCConnector::ProtocolBuffers::DGCommand commandObj;
commandObj.set_type(DS3DExcite::Net::PVCConnector::ProtocolBuffers::DGCommand_Type_SwitchVariants);
commandObj.set_id(3);
DS3DExcite::Net::PVCConnector::ProtocolBuffers::SwitchVariants *objVarState;
objVarState = commandObj.MutableExtension(DS3DExcite::Net::PVCConnector::ProtocolBuffers::SwitchVariants::command);
DS3DExcite::Net::PVCConnector::ProtocolBuffers::SwitchVariants_VariantState *state = objVarState->add_variants();
state->set_state("OFF");
state->set_variant("M_Carpaint_3");
我序列化了消息
int size = commandObj.ByteSize();
int sizeSize = sizeof(int);
std::vector<char> data(size ,0);
memcpy(data.data(), &size, sizeSize);
data.resize(size + sizeSize );
commandObj.SerializeToArray(static_cast<void*>(&(data[0])+sizeSize) ,size);
QByteArray byteArray = QByteArray::fromRawData(static_cast<const char*>(data.data()), data.size());
我在Qtcp套接字上将此消息发送到服务器,该服务器对消息进行反序列化并从消息中提取信息。
在服务器端,这是要读取的代码
uint32 pendingData = 0;
rcvSocket->HasPendingData(pendingData); //rcvSocket is the serversside socket
if (pendingData == 0)
{
UE_LOG(PVCConnector, Warning, TEXT("Lost connection to client."));
break;
}
TArray<char> newData; //customized Array template
newData.InsertZeroed(0, pendingData);
int32 bytesRead = 0;
rcvSocket->Recv(reinterpret_cast<uint8*>(newData.GetData()), pendingData, bytesRead);
data += newData;
然而,在服务器端,所需的信息出现在:: google :: protobuf :: Message的未知字段中。可能是什么原因?
答案 0 :(得分:0)
当我发送足够多的消息时,我遇到了类似的问题。我们认为,当消息分成几个网络包时会发生这种情况。我们使用blob来防止这种情况,并且它可以工作。关于blob,它的技术to send message length, before message
答案 1 :(得分:0)
我能够解决问题。有2个问题
1)我转换为ByteArray的方式 我换了
QByteArray byteArray = QByteArray::fromRawData(static_cast<const char*>(data.data()), data.size());
带
QByteArray *byteArray = new QByteArray(reinterpret_cast<const char*>(data.data()), data.size());
2)我在套接字上发送消息的方式。我刚用过
const int nbBytes = itM->second->write(qByteArray);
而不是使用QTextStream