Qt,客户端 - 服务器关系

时间:2017-10-20 20:11:11

标签: c++ qt

我是网络和互联网领域的新人,因此想为可能是愚蠢的问题道歉。我不明白是否有其他方法将数据从客户端套接字发送到服务器的axcept,使用方法QIODevice::write(QByteArray& )将数据放入流中。如果这是服务器应该识别究竟是什么数据发送给它的唯一方法?例如,我们可能会将QString消息作为常规输入数据,但有时也会QString作为未来数据的进一步接收者的名称。可以描述所有变体,但连接到readyRead()信号的插槽似乎是巨大的 在这种情况下的大小。

最终,有没有办法将数据导向某些确切的服务器功能?

2 个答案:

答案 0 :(得分:0)

Qt Solutions拥有一个可轻松制作Qt服务器的库:

Qt Solutions

和Json格式这是一种很好的沟通方式

答案 1 :(得分:0)

您需要定义两侧的comman数据类型(客户端和服务器)。在发送数据包之前,您应该将数据包的大小写入数据包的前四个字节。在服务器端检查从客户端接收的数据的大小,前四个字节。并反序列化您在客户端如何序列化的数据。我长时间使用这种方法,今天出现了任何问题。我会为你提供示例代码。

客户端:

QBuffer buffer;
buffer.open(QIODevice::ReadWrite);
QDataStream in(&buffer);
in.setVersion(QDataStream::Qt_5_2);
in << int(0);   // for packet size 
in << int(3);   // int may be this your data type or command
in << double(4);            // double data
in << QString("asdsdffdggfh");  // 
in << QVariant("");
in << .... // any data you can serialize which QDatastream accept
in.device()->seek(0);                   // seek packet fisrt byte 
in << buffer.data().size();             // and write packet size
array = buffer.data();

this->socket->write(arr);
this->socket->waitForBytesWritten();

服务器端:

QDatastream in(socket);

//define this out of this scope and globally
int expectedByte = -1;



if( expectedByte < socket->bytesAvailable() && expectedByte == -1 )
{
    in >> expectedByte;
}

if(expectedByte - socket->bytesAvailable()- (int)sizeof(int) != 0){
  return;
}

// if code here, your packet received completely
int commandOrDataType;
in >> commandOrDataType;
double anyDoubleValue;
in >> anyDoubleValue;
QString anyStringValue;
in >> anyStringValue;
QVariant anyVariant;
in >> anyVariant;
// and whatever ...

// do something with above data


//you must set expectedByte = -1;
// if your proccessing doing any thing at this time there is no any data will be received while expectedByte != -1,  but may be socket buffer will be filling. you should comfirm at the begining of this function
expectedByte = -1;

希望这有用! :)