我想知道复杂的软件客户端 - 服务器如何管理流。 例如,当我玩反恐精英时,他们会从客户端到服务器和服务器向客户端发送大量数据包。管理流的最佳方法是什么?
我想:
服务器向客户端发送数据
void Server::send(const QString &message)
{
QByteArray paquet;
QDataStream out(&paquet, QIODevice::WriteOnly);
out << (quint16) 0; //packet size
out << (quint8)14; //packet type to execute a special action on the client
out << message; // data, here string but can be another class
out.device()->seek(0);
out << (quint16) (paquet.size() - sizeof(quint16)); //write packet size
socket->write(paquet);
}
客户端从服务器接收数据
void Client::receiveData()
{
QDataStream in(socket);
if (size_packet == 0) // size_packet, initilize to 0
{
if (socket->bytesAvailable() < (int)sizeof(quint16))
return;
in >> tailleMessage;
}
if (socket->bytesAvailable() < tailleMessage)
return;
//now I can get data
quint8 typeObject;
in >> typeObject;
switch(typeObject){
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
...
...
case 14:
QString data; //can be another custom class
in >> data;
write(data);
break;
//my solution, the server can execute an action on the client depending type packet
}
size_packet= 0;
}
我想我必须在客户端和服务器之间使用共享库并序列化我的自定义类。
但我应该这样做吗?使用json或xml或协议缓冲区(谷歌)或其他???
答案 0 :(得分:0)
正如@MrEricSir所述,游戏通常使用UDP协议。它使用数据报,而不是流。因此在数据传输过程中可能会丢失一些数据报。您的协议应该处理丢失的数据。通常这样的协议是二进制的,它们不会因为开销而使用xml,json或protobuf。