My Problem: With net.Read... Methods copy only the number of bytes of the size of the given byte-array or slice. I dont want to allocate the maximum UDP datagram of 64 kB every time of course.
Is there a go way to determine the size of the datagram (which is in the datagram header) or read again until the datagram is completely read?
Try ReadFromUDP:
func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
ReadFromUDP reads a UDP packet from c, copying the payload into b. It returns the number of bytes copied into b and the return address that was on the packet.
The packet size should be available from n
, which you can then use to define a custom slice (or other data structure) to store the datagrams in. This relies on the datagram size not changing during the session, which it really shouldn't.
Usually in a UDP protocol packet sizes are known in advance, and it's usually much smaller, in the order of 1.5k or less.
What you can do is preallocate a maximum size static buffer for all reads, then once you know the size of the datagram you've read from the socket, allocate a byte array with the actual size and copy the data to it. I don't think you can do extra reads of the same datagram.