计算 C# UdpClient.Send() 数据报中的字节数

发布于 2024-07-16 20:53:48 字数 90 浏览 6 评论 0原文

在 C# 中,为了使用 UdpClient.Send() 方法,我必须提供要发送的字节数作为参数之一。

在发送数据报之前如何计算数据报中的字节数?

In C#, in order to use the UdpClient.Send() method I must provide as one of the parameters the number of bytes I am sending.

How do I calculate the number of bytes in a datagram before sending it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疾风者 2024-07-23 20:53:48

您向 UdpClient.Send() 传递一个字节数组 (Byte[])、一个整数大小和一个 IPEndPoint。 如果您要发送整个字节数组,仅此而已,作为数据报的有效负载,您可以使用数组的 Length 属性,如下所示:

UdpClient udpClient = new UdpClient();
IPAddress ipAddress = Dns.Resolve("www.contoso.com").AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11004);    

Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
try{
    udpClient.Send(sendBytes, sendBytes.Length, ipEndPoint);
}
catch ( Exception e ){
    Console.WriteLine(e.ToString());    
}

也许这里的困惑在于您认为必须计算将要发送的字节数。通过电线发送出去? 实际需要的只是有效负载的大小(您实际想要在此数据报中发送的所提供字节数组的部分)。 图书馆将完成剩下的工作。

示例和信息此处

You pass UdpClient.Send() an array of bytes (Byte[]), an integer size, and an IPEndPoint. If you are sending the entire byte array, nothing more and nothing less, as your datagram's payload, you can just use the Length property of arrays as follows:

UdpClient udpClient = new UdpClient();
IPAddress ipAddress = Dns.Resolve("www.contoso.com").AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11004);    

Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
try{
    udpClient.Send(sendBytes, sendBytes.Length, ipEndPoint);
}
catch ( Exception e ){
    Console.WriteLine(e.ToString());    
}

Perhaps the confusion here is that you think you have to count the number of bits that will be sent out over the wire? What is actually required is just the size of the payload (the part of the provided byte array you actually want to send in this datagram). The library will do the rest.

Examples and info here.

乖乖公主 2024-07-23 20:53:48

不确定您使用什么语言来实现此 UDP 客户端。 在 C++ 中,sizeof 运算符提供字节数。 其他方法是使用 strlen() 或其 unicode 变体 & 乘以数据类型大小。

Not sure what language you are using to impement this UDP client. In C++, sizeof operator provides the number of bytes. Other approach would be to use strlen() or their unicode variants & multiply by the data type size.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文