V
V
Vanes Ri_Lax2020-12-22 14:34:30
C++ / C#
Vanes Ri_Lax, 2020-12-22 14:34:30

How to understand that the browser sent all the data?

I am writing a small web service that will respond to a browser request.
As I understand it, according to the rules of the HTTP protocol, when connecting, the browser sends headers to the server, but how to understand that the browser has finished transmitting data to the server and is waiting for a response from the server?
Now I do it like this:

static string ReadMessage(SslStream sslStream)
        {
            byte[] buffer = new byte[8];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            while (true)
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("\r\n\r\n") != -1)
                {
                    break;
                }
            }

            Console.WriteLine(messageData);
            return messageData.ToString();
        }

But it doesn't always work correctly, sometimes an exception like:
System.IO.IOException: "Не удается прочитать данные из транспортного соединения: Попытка установить соединение была безуспешной, т.к. от другого компьютера за требуемое время не получен нужный отклик, или было разорвано уже установленное соединение из-за неверного отклика уже подключенного компьютера."

As I understand it, this happens because the program is trying to read data from the socket, but they are not there. How can I read the data correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2020-12-22
@vabka

If you have a line break not through CLRF, then you will never exit the loop and try to read something from the socket when it is already closed.
In general, it's better not to reinvent the http server and take a ready-made asp net core

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question