问题描述
在一个项目中,我有多个UDP数据发送者,但只有一个接收者.
In a project I have multiple senders of UDP data, but only a single receiver.
如果流量增加,则接收器会忘记"很多数据包.我知道这是UDP固有的问题,但是我想减少丢失的数据包的数量.
If traffic gets higher, the receiver "forgets" lots of packets. I know that this is a problem inherent to UDP, but I want to minimize the number of lost packets.
我之前已经阅读过这个 SO问题!
I have read this SO question before!
这是我的代码(请原谅大量的代码块,但我希望示例可以独立存在)
Here is my code (Please excuse the massive code blocks, but I wanted the example to be self contained)
发送方:
public class UdpSender
{
private static int portNumber = 15000;
public void Send(string data)
{
var udpServer = new UdpClient();
var ipEndPoint = new IPEndPoint(IPAddress.Broadcast, portNumber);
byte[] bytes = Encoding.ASCII.GetBytes(data);
udpServer.Send(bytes, bytes.Length, ipEndPoint);
udpServer.Close();
}
}
class Program
{
static void Main(string[] args)
{
var sender = new UdpSender();
var count = 100000;
for (var i = 0; i < count; ++i)
{
sender.Send(i.ToString());
}
Console.ReadKey();
}
}
接收方:
public class UDPListener
{
private static int portNumber = 15000;
private readonly UdpClient udp = new UdpClient(portNumber);
public volatile int CountOfReceived = 0;
public void StartListening()
{
this.udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
Interlocked.Increment(ref CountOfReceived);
IPEndPoint ip = new IPEndPoint(IPAddress.Any, portNumber);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
StartListening();
}
}
class Program
{
static void Main(string[] args)
{
var listener = new UDPListener();
listener.StartListening();
while (true)
{
Console.WriteLine(listener.CountOfReceived.ToString("000,000,000"));
}
}
}
现在,如果我并行启动5个发件人应用程序,则仅收到大约四分之一的消息.这仅在我的本地计算机上.
Right now if I start 5 sender applications in parallel, only about a quarter of the messages is received. This is only on my local machine.
我该怎么做才能最大程度地减少丢包?
推荐答案
考虑到您在旅途中发送数据包的速度,我会说接收器缓冲区可能会花一点时间-增加缓冲区大小(如此处所示)可以解决这个问题.
thinking about the speed you're sending your packets on their trip i would say that the sinks buffer might be filled in a bit of time - increasing the buffer size (as shown here) could solve this issue, i guess.
这篇关于具有多个发送器和一个接收器的UDP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!