O
O
oleg_ods2020-11-20 14:43:49
ASP.NET
oleg_ods, 2020-11-20 14:43:49

How correctly to receive data from a socket (TcpClient)?

Good afternoon!

There is an API that sends JSON through sockets. The problem is that with large responses, TcpClient does not always have time to receive all the data. Please tell me how to solve this problem.

I accept it this way. Thread.Sleep() partially solves the problem, but firstly, not always, and secondly, it slows down other lighter requests.

using (var client = new TcpClient(_settings.Host, _settings.Port))
            {
                using (var ns = client.GetStream())
                {
                    using (var ms = new MemoryStream())
                    {
                        await ns.WriteAsync(requestData, 0, requestData.Length);                        

                        do
                        {
                            byte[] responseData = new byte[client.ReceiveBufferSize];
                            int recivedBytes = await ns.ReadAsync(responseData, 0, responseData.Length);
                            await ms.WriteAsync(responseData, 0, recivedBytes);
                            Thread.Sleep(400);
                        } while (client.Available > 0);

                        var response = ms.ToArray();

                        var result = Encoding.UTF8.GetString(response);

                        return ParseResponse(result);
                    }
                }
            }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
oleg_ods, 2020-11-25
@oleg_ods

Solved the problem using StreamReader

using (var client = new TcpClient(_settings.Host, _settings.Port))
            {
                using (var ns = client.GetStream())
                {
                    using (var sr = new StreamReader(ns, Encoding.UTF8))
                    {
                        await ns.WriteAsync(requestData, 0, requestData.Length);

                        var result = await sr.ReadToEnd();

                        return ParseResponse(result);
                    }
                }
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question