Go: How to receive a whole UDP Datagram

huangapple go评论83阅读模式
英文:

Go: How to receive a whole UDP Datagram

问题

我的问题:使用net.Read...方法只复制给定字节数组或切片大小的字节数。当然,我不想每次都分配最大的64 kB UDP数据报。

有没有一种go的方法可以确定数据报的大小(数据报头中的大小),或者重复读取直到完全读取数据报?

英文:

My Problem: With net.Read... Methods copy only the number of bytes of the size of the given byte-array or slice. I don't 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?

答案1

得分: 2

尝试使用ReadFromUDP函数:

func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)

ReadFromUDP从连接c中读取一个UDP数据包,并将数据包的有效负载复制到b中。它返回复制到b中的字节数以及数据包的返回地址。

数据包的大小可以从n中获取,然后您可以使用它来定义一个自定义的切片(或其他数据结构)来存储数据报。这依赖于会话期间数据报大小不会改变,实际上它不应该改变。

英文:

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.

答案2

得分: 0

通常在UDP协议中,数据包的大小是预先知道的,通常要小得多,大约为1.5k或更小。

你可以预先分配一个最大大小的静态缓冲区用于所有读取操作,然后一旦你知道从套接字读取的数据报的大小,就可以分配一个实际大小的字节数组,并将数据复制到其中。我认为你不能对同一个数据报进行额外的读取操作。

英文:

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.

huangapple
  • 本文由 发表于 2014年2月24日 18:09:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/21984569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定