UDP with multiple sender and one single receiver

2019-06-04 04:05发布

问题:

In a project I have multiple senders of UDP data, but only a single receiver.

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.

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)

Sender side:

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();
    }
}

Receiver side:

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"));
        }

    }
}

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.

What can I do to minimize packets lost?

回答1:

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.