Send large data on UDP socket

2019-06-22 06:24发布

问题:

I need to send and receive very large data using udp. Unfortunately udp provides 8192 bytes per diagram, so there is need to divide data into smaller pieces. I'm using Qt and QUdpSocket. There is a QByteArray with length of 921600 I want to send to client. I want to send 8192 bytes each time.

What is the fast way to split a QByteArray?

回答1:

You can use the QByteArray.mid(int start, int len) method (see documentation here) to get a QByteArray of length len starting from start.

Just make len your datagram size and start with 0*len, 1*len, 2*len, ... until everything is sent.



回答2:

You should never need to explicitly split the data, just step through it 8 KB at a time. Typically the functions that write data to a socket (including QUdpSocket::writeDatagram, it seems) accept a pointer to the first byte and a byte count, so you can just provide a pointer into the array.

Do note that sending 8 KB datagrams is quite aggressive; they will very likely be fragmented at the IP layer which can affect delivery speed and reliability negatively.

Research the concept of "path MTU", and try to use that for the sends, it might be faster although it will result in more datagrams.



回答3:

Actually the length field on a UDP header is 16 bits so a UDP datagram can be up to ~65k (minus the size of the header stuff).

However, as unwind pointed out, it will most likely be fragmented along the way to fit the smallest MTU on the path to the destination.

8192 bytes is the default receive buffer size for Windows operating systems. The MTU is likely 1500 bytes if you are using Ethernet. Any UDP datagram larger than that will be fragmented. If your datagram encounters a device along the route with an even smaller MTU, it will be fragmented yet again.



标签: qt udp