Answer the question
In order to leave comments, you need to log in
Asynchronous UDP client in C#. Where is the data being received?
I read this post - https://habr.com/en/post/238377 . Looks interesting.
But I can not understand where the response from the server is received.
I see the code
public async Task<byte[]> SendReceiveAsync(byte[] msg, string ip, int port, int timeOut)
{
var endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
var tcs = new TaskCompletionSource<byte[]>();
try
{
var tokenSource = new CancellationTokenSource(timeOut);
var token = tokenSource.Token;
if (!_tcsDictionary.ContainsKey(endPoint)) _tcsDictionary.TryAdd(endPoint, tcs);
_client.Send(msg, msg.Length, ip, port);
var result = await tcs.Task.WithCancellation(token);
return result;
}
finally
{
_tcsDictionary.TryRemove(endPoint, out tcs);
}
}
static class TaskExtension
{
public static async Task<T> WithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
using (cancellationToken.Register(
s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs))
if (task != await Task.WhenAny(task, tcs.Task))
throw new OperationCanceledException(cancellationToken);
return await task;
}
}
Answer the question
In order to leave comments, you need to log in
There is below code
Task.Run(() =>
{
IPEndPoint ipEndPoint = null;
while (true)
{
try
{
var receivedBytes = _client.Receive(ref ipEndPoint);
TaskCompletionSource<byte[]> tcs;
if (_tcsDictionary.TryGetValue(ipEndPoint, out tcs)) tcs.SetResult(receivedBytes);
}
catch (SocketException)
{
;//при невозможности соединения продолжаем работать
}
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question