C# socket Receive Problem of socket receiving data

LoveC 61 Reputation points
2022-09-05T20:43:00.507+00:00

When I try to accept website images.I use Socket.Receive().However, the data size it accepts does not match the actual data size.Moreover, the size of the received data changes every time.I tried to add "thread. Sleep (500)" before "socket. Receive", and it will be normal.So I think it may be that the program did not wait for the data transfer to complete when reading the data.So I tried the method of receiving data in a loop, but I can't know under what circumstances the data can be received completely.Oh.How can I solve this problem.thanks!!!!

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,909 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Keshav Kumar 1 Reputation point
    2022-09-05T23:28:43.607+00:00

    Hello,
    I see that the example for using Socket.Receive at the below msdn link, example code is at the end of this reply:
    https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.socket.receive?view=net-6.0

    Have you tried in the same way and is it not working even after using code as below given example? Please let me know if it does not work for you.

    // Receive the host home page content and loop until all the data is received.
    Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
    strRetPage = "Default HTML page on " + server + ":\r\n";
    strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

    while (bytes > 0)
    {
    bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
    strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
    }


  2. Bruce (SqlWork.com) 64,901 Reputation points
    2022-09-06T00:50:51.903+00:00

    Http images are read via http 1.1 protocol. There are headers, one that give the body length. See

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview

    As keep alive is usually set, so the next request will not require a new connection, the data length is important. If no length is sent, than a fin is used.

    Note: you must read and parse the headers, before you know the length. The headers will also tell you of and compression used.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.