Go:如何接收整个 UDP 数据报 [英] Go: How to receive a whole UDP Datagram

查看:33
本文介绍了Go:如何接收整个 UDP 数据报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

解决方案

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.

这篇关于Go:如何接收整个 UDP 数据报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆