Thanks alot all of you, especially Thiago,
I finally got it working. The trick was to read the data after the
QTcpSocket connection was closed rather than reading it when
readyRead() was emitted.
Here is my server code:
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << ui->lblScreenShot->pixmap()->toImage();
QTcpSocket *client = pixmapServer->nextPendingConnection();
connect (client, SIGNAL(disconnected()), client, SLOT(deleteLater()));
client->write(block);
qDebug() << block.size();
client->disconnectFromHost();
It reads the QPixmap from a label, and here is the client code:
QDataStream in(socket);
in.setVersion(QDataStream::Qt_4_7);
QImage img;
in >> img;
ui->screenshotLabel->setPixmap(QPixmap::fromImage(img));
As you can see, its all so choppy, but at least I can start up from there.
Thanks.
____________________________________________-
That is correct.
But note you said "once you've read all the data". So the question is still:
how do you know that you've read it all and that no bytes remain, still to be
received by the network?
There are usually two ways of doing this (from your "programming 101" class):
- send the length in advance
- send a sentinel afterwards
C strings use a sentinel afterwards (the NUL). You can't send a specific byte
sequence since the data you're sending is arbitrary and binary. So the only
sentinel you can send is the "connection close".
Given that the OP was closing the socket just after writing the pixmap data,
then sending the length in advance is unnecessary. Conclusion:
Sender:
connect(socket, SIGNAL(disconnected()), socket, SLOT(deleteLater()));
socket->connectToHost(...);
socket->write(block);
socket->disconnectFromHost();
socket = 0;
Receiver:
socket = server->nextPendingConnection();
connect(socket, SIGNAL(disconnected()), this, SLOT(readAllData()));
void readAllData()
{
QByteArray data = socket->readAll();
delete socket;
}
本文介绍了一种使用Qt框架通过TCP连接发送和接收图片的方法。关键在于在连接关闭后读取数据,而不是在readyRead信号发出时读取。文章提供了服务器端和客户端的代码示例,并讨论了如何确保所有数据都被正确读取的技术细节。
6122

被折叠的 条评论
为什么被折叠?



