简体   繁体   中英

Sending packets with UDP protocol

I am using Qt to build a network project. My project sends files as packets, every packet is 1K size, I am using UDP protocol.

The problem is when I try to send files with big size in Megabytes, the function writeDatagram() hanging and the for loop stops (as I feel).

How can I solve that? Here goes code I use for sending packets. The packets stored in vector.

for(int i=0;i<vector.size();i++)
{
    char *pkt=(char*)&vector.at(i);
    MsgPacket *p=(MsgPacket*)&vector.at(i);
    UDPSocket->writeDatagram(pkt,sizeof(*p),(*addr),(*port));
    UDPSocket->waitForBytesWritten();
    qDebug()<<"packet"<<i<<"sent";
}

Your call to UDPSocket->waitForBytesWritten(); makes your loop wait until the socket is flushed. Either don't call UDPSocket->waitForBytesWritten(); , or put this routine in a separate Thread, so it wont block.

Quote of the documentation for waitForBytesWritten() :

This function can operate without an event loop. It is useful when writing non-GUI applications and when performing I/O operations in a non-GUI thread.

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.

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