2017-10-20 87 views
0

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

最后,有没有办法将数据引导到某个确切的服务器功能?

+1

我不太确定你的问题是什么,但在我看来,你似乎在设计*协议*。即某种方式说“此消息包含此数据”和“此其他消息包含其他数据”。 –

+1

您的服务器和客户端需要知道如何通信。也就是说,他们必须就一个通用的协议达成一致 - 比如“我总是会发送两个字节来识别将要发生的事情的类型,然后我会发送4个字节来表示'事情'的大小,然后数据将会跟随”;那么你会回复“我们已经同意的形式的东西”等 - 或类似的东西..你不能只是发送任意的“东西”,并期望另一端猜测它是什么。 –

+0

@JesperJuhl所以协议只是关于数据如何识别的规则和描述的集合? –

回答

0

Qt的解决方案有一个图书馆,使轻松的Qt服务器:

Qt Solutions

和JSON格式,它是沟通

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; 

希望这会很有帮助! :)