I'm working on a console application that needs to receive data from two local endpoints and subsequently send that data to two remote endpoints - in parallel. I have the code to recv/send data in an Task that looks like this:
public async Task RecvAndSend(DataObj data, bool isRequest)
{
try
{
using var recv = new UdpClient(data.localPort);
using var send = new UdpClient();
var remoteEndpoint = new IPEndPoint(data.remoteAddress, data.remotePort);
while (true)
{
try
{
byte[] res = (await recv.ReceiveAsync()).Buffer;
await send.SendAsync(res, res.Length, remoteEndpoint);
Console.Write(isRequest ? "-" : "~");
}
catch (Exception ex) {
Console.WriteLine("Exception thrown in while loop: {0}", ex.Message);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This task takes in 2 params. The first being data related to the local port this task will receive data on and the remote address it will be forwarding that data to.
As I mentioned, two instances of this task need to run in parallel. One instance is referred to as the "Request" task, and the other is the "Response" task. I'm passing in a bool (isRequest) that I can use to write a symbol to the console for whichever task just completed an iteration of the while loop.
I am starting these parallel tasks like so:
Task t1 = RecvAndSend(requestData, true);
Task t2 = RecvAndSend(responseData, false);
await Task.WhenAll(t1, t2);
The problem is - the first task will begin to receive/send data, but as soon as the second task begins to receive/send data, the first task stops. So my output looks something like this:
-------~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
What I expect to see is:
-~-~-~-~-~-~
Maybe not that in sync but you get the idea.
I've tried instantiating separate UdpClients for sending and receiving inside of each task and I've also tried declaring global clients dedicated to receiving/sending and using a lock mechanism inside the task.
Nothing has worked as expected. I'm unsure at this point if its even possible to have 2 threads with 2 UdpClients each receiving and sending at the same time.
I was able to resolve this problem. My issue turned out to be related to port number. I was creating a separate client to send data that was binding to a random available port chosen by the OS. Upon receiving that data, the destination server began responding on that random port rather than the port it initially started sending data from. For that reason my receiving client stopped dead in its tracks. There was no longer any data coming in through the port it was expecting data from.