简体   繁体   中英

How do I load balance received udp packets over multiple threads?

I'm creating an application with will send and receive vast amount of data via udp packets. I want to have the ability to scale the processing of these requests by adding or diminishing more worker threads. However when I add a second thread and start waiting for data I get the following error.

“Only one usage of each socket address (protocol/network address/port) is normally permitted”

The Code:

static void Main(string[] args)
{
    Console.WriteLine("Running...");

    Thread threadA = new Thread(new ThreadStart(ProcessMessage));
    Thread threadB = new Thread(new ThreadStart(ProcessMessage));

    threadA.Start();
    threadB.Start();

    Console.WriteLine("Press any key.");
    Console.ReadLine();
}

private static void ProcessMessage()
{
    using (var udpClient = new UdpClient(11000))
    {
        var sender = new System.Net.IPEndPoint(IPAddress.Any, 11000);
        var data = udpClient.Receive(ref sender);

        // Do work
    }
}

The error is very clear but then my question is: How do I correctly divide the work among multiple threads?

Thanks for the help and sorry for any spelling mistakes. I'm not a native english speaker.

The comment from C.Gonzalez was very helpful, so I will put it here as the correct answer.

The usual way to handle high volume UDP is to have one thread just consuming data as fast as it can (and putting the content of the messages into a queue). (Any moderately new hardware can receive data as fast as the network can send it) One or more other threads empty and process the data. If a response is necessary, it can be put into an outgoing queue for another dedicated thread to send messages out (you can use the same socket form this dedicated thread). Again, any relatively new hardware can send and receive duplex mode at wire speed with ease.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM