qtcpsocket send and recieve the image from youself
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;
}