S
S
sudo rm -rf /2021-02-18 17:13:22
C++ / C#
sudo rm -rf /, 2021-02-18 17:13:22

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


And expansion
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;
        }
    }


And I don't see where, for example, _client.Receive() is called.

Can you please tell me where the results are coming from?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
none7, 2021-02-18
@MaxLevs

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)
                    {
                        ;//при невозможности соединения продолжаем работать
                    }

                }
            });

Here, using tcs.SetResult , data is passed to the first piece of code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question