Go: How to receive a whole UDP Datagram

2020-07-13 09:32发布

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?

标签: go udp
2条回答
孤傲高冷的网名
2楼-- · 2020-07-13 10:12

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.

查看更多
家丑人穷心不美
3楼-- · 2020-07-13 10:13

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.

查看更多
登录 后发表回答