I'm trying to send pictures via a QTCPsocket, with localhost (127.0.0.1) it works fine. If I'm sending it to an other pc via ethernet, sometimes Qt receveices it in 2 times, see debug output.
How can i fix it?
Server side:
void server::writePic(QString fileName)
{
name = QString("%1.png").arg(counter);
counter++;
qDebug() << name;
pic.load(fileName, "PNG");
pic.setText("name",name);
pic.setText("datum","20-3-2018");
QByteArray ba; // Construct a QByteArray object
QBuffer buffer(&ba); // Construct a QBuffer object using the QbyteArray
pic.save(&buffer, "PNG"); // Save the QImage data into the QBuffer
qDebug() << ba;
socket->flush();
socket->write(ba); // Send the QBuffer (QbyteArray) over a socket
socket->waitForBytesWritten();
socket->flush();
}
Client side:
void Client:: readyRead()
{
ImageBuffer->open(QIODevice::ReadWrite);
socket->waitForReadyRead(1);
QByteArray Temp;
Temp = socket->readAll();
ImageBuffer->write(Temp);
pic.loadFromData(ImageBuffer->buffer());
std::stringstream fileName;
fileName <<"C:/pics/" << pic.text("name").toStdString();
if(!pic.isNull())
{
qDebug() << "Image file was received ";
qDebug() << pic.text("name");
qDebug() << pic.text("datum");
qDebug() << "size = " << Temp.size();
pic.save(fileName.str().c_str(),"PNG");
}else{
qDebug() << "Pic is NULL";
qDebug() << "size = " << Temp.size();
}
}
Server side:
"C:/.../Analysis/test_images/Foto01.png"
"1.png"
We wrote: 25156
File has been removed
"C:/.../Analysis/test_images/Foto02.png"
"2.png"
We wrote: 26755
File has been removed
Client side:
Not succeeded:
Pic is NULL
size = 18980
Pic is NULL
size = 6176
Succeeded:
Image file was received
"2.png"
"20-3-2018"
size = 26755
Nothing ensures you to receive your picture in a single read. That's true. one solution is to encapsulate your picture in a frame you will define, containing info about that picture. One simple (and not really bulletproof) way would be to add the size of your picture as the first 4 bytes of your frame. On the receive side, your could read it, and wait for additional data as long as you did nor receive at lease the expected side. For sure you should improve structure and processing to handle packet loss and spurious disconnections.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.