证时,会出现信息残缺,我的解决方案是使用延时策略,但是这并不是长久之计。
按照官方给的例子:
服务端发送数据:
void Server::sendFortune()
{
? ? QByteArray block;
? ? QDataStream out(&block, QIODevice::WriteOnly);
? ? out.setVersion(QDataStream::Qt_4_0);
? out << (quint16)0;
? ? out << fortunes.at(qrand() % fortunes.size());
? ? out.device()->seek(0);
? ? out << (quint16)(block.size() - sizeof(quint16));
?QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
? ? connect(clientConnection, SIGNAL(disconnected()),
? ? ? ? ? ? clientConnection, SLOT(deleteLater()));
? clientConnection->write(block);
? ? clientConnection->disconnectFromHost();
}
客户端接受数据:
void Client::readFortune()
{
? ? QDataStream in(tcpSocket);
? ? in.setVersion(QDataStream::Qt_4_0);
? ? if (blockSize == 0) {
? ? ? ? if (tcpSocket->bytesAvailable() < (int)sizeof(quint16))
? ? ? ? ? ? return;
? ? ? ? in >> blockSize;
? ? }
? ? if (tcpSocket->bytesAvailable() < blockSize)
? ? ? ? return;
QString nextFortune;
? ? in >> nextFortune;
? ? if (nextFortune == currentFortune) {
? ? ? ? QTimer::singleShot(0, this, SLOT(requestNewFortune()));
? ? ? ? return;
? ? }
? ? currentFortune = nextFortune;
? ? statusLabel->setText(currentFortune);
? ? getFortuneButton->setEnabled(true);
}
缺点是每收发一回合信息,都要重连一次。