我正在Qt中编写一个简单的客户端-服务器应用程序,但是在客户端读取数据时遇到了问题。数据到达了客户端,但是我无法将它们提取到类中的变量中,它们似乎已被破坏。
代码如下:
接收器:
void ClientTcpHelper::UnpackData(){
stream=new QDataStream (&this->socket);
stream->startTransaction();
*stream>>P1_X>> P1_Y>>P2_X>> P2_Y>>Ghost1_X>>Ghost1_Y>>Ghost2_X>>Ghost2_Y>> Ghost3_X>>Ghost3_Y>> Ghost4_X>>Ghost4_Y>> Ghost5_X>>Ghost5_Y
>> Ghost6_X>>Ghost6_Y>>Ghost1_state>>Ghost2_state>>Ghost3_state>>Ghost4_state>>Ghost5_state>>Ghost6_state>>P1_HP>>P2_HP>>P1_Score>>P2_Score;
if(!stream->commitTransaction()){
return;
}
delete stream;
qDebug()<<"P1_X"<<P1_X<<" P1_Y: "<<P1_Y<<"P1 score:"<<P1_Score <<endl;
qDebug()<<"P2_X"<<P2_X<<" P1_Y: "<<P2_Y<<"P1 score:"<<P2_Score <<endl;
emit DataReceived(); }
发件人(服务器端):
void ServerTcpHelper::SendPacket(){
qDebug()<<"sending.."<<endl;
stream=new QDataStream (&this->Data,QIODevice::OpenModeFlag::ReadWrite);
*stream<<P1_X<<P1_Y<<P2_X<<P2_Y<<Ghost1_X<<Ghost1_Y<<Ghost2_X<<Ghost2_Y<< Ghost3_X<<Ghost3_Y<< Ghost4_X<<Ghost4_Y<< Ghost5_X<<Ghost5_Y
<< Ghost6_X<<Ghost6_Y<<Ghost1_state<<Ghost2_state<<Ghost3_state<<Ghost4_state<<Ghost5_state<<Ghost6_state<<P1_HP<<P2_HP<<P1_Score<<P2_Score;
if(P1socket->state()==QTcpSocket::ConnectedState){
P1socket->write(Data);
P1socket->waitForBytesWritten(50);
}
if(P2socket->state()==QTcpSocket::ConnectedState){
P2socket->write(Data);
P2socket->waitForBytesWritten(50);
}
delete stream;
Data.clear();}
来自接收器的调试流显示有效值 (例如P1_X:960 P1_Y:40 P1_Score:48),但是这些值似乎并没有持续下去,当UnpackData完成时,它们将被清零(我的意思是-当我尝试在主程序中使用ClientTCPHelper的Getters获得它们时)。