简体   繁体   English

通过qt TCP / IP发送图片

[英]Sending pictures via qt TCP/IP

I'm trying to send pictures via a QTCPsocket, with localhost (127.0.0.1) it works fine. 我正在尝试通过QTCPsocket发送图片,使用localhost(127.0.0.1)可以正常工作。 If I'm sending it to an other pc via ethernet, sometimes Qt receveices it in 2 times, see debug output. 如果我通过以太网将其发送到另一台PC,有时Qt会两次接收到它,请参见调试输出。

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();
   }
}

Debug output 调试输出

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. 一种简单(并非真正防弹)的方法是将图片的大小添加为帧的前4个字节。 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. 当然,您应该改进结构和处理以处理数据包丢失和虚假断开连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM