【发布时间】:2014-09-29 12:23:28
【问题描述】:
在一个项目中,我有多个 UDP 数据发送者,但只有一个接收者。
如果流量变大,接收方会“忘记”大量数据包。我知道这是 UDP 固有的问题,但我想尽量减少丢失数据包的数量。
我之前读过this SO question!
这是我的代码(请原谅大量的代码块,但我希望示例是独立的)
发送方:
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 个发送方应用程序,则只会收到大约四分之一的消息。这仅在我的本地计算机上。
我可以做些什么来最大程度地减少数据包丢失?
【问题讨论】:
-
考虑到您在旅途中发送数据包的速度,我会说接收器缓冲区可能会在一段时间内填满 - 我想增加缓冲区大小可以解决这个问题。
-
非常感谢,会试试这个!
-
是的,这真的很有帮助!已将缓冲区大小增加到 8mb,现在可以接收所有消息。这种大小的缓冲区有什么问题吗?
-
@Matt 现在我选择了 8MB 作为我的缓冲区大小,因为那时所有的数据包都被接收到了。关于“巨大”大小的缓冲区是否存在任何已知问题? (因为我的机器上的默认大小只有 8K)。如果您发表评论作为答案,我会接受。
标签: c# sockets networking udp packet