2
votes

I'm trying to understand the use of a buffer in the socket scheme of things. Here is what I understand, and if someone could tell me if I'm correct or give feedback to where I might be misunderstanding that would be great.

Using the Asynchronous Sockets detailed on MSDN example (all below is with reference to that example)

Below describes a state object of which I understand the point of:

// State object for reading client data asynchronously
public class StateObject
{
    // Client  socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
}

Now it says the buffer is 1024 bytes. When you recieve data, you are only asking for 1024 bytes at a time? And in the async method ReceiveCallback, it only ask for 1024 and then says this may not be all of the data, so now retrieve the next 1024.

So basically, the input stream sent to the socket is read in 1024 byte chunks and you keep reading till you've hit an end point (by you're own definition)?

1

1 Answers

3
votes

So basically, the input stream sent to the socket is read in 1024 byte chunks and you keep reading till you've hit an end point (by you're own definition)?

Correct. Since TCP is just a stream of data there is really no way of know the length of each if your messages in the stream (unless you always have a fixed length). hence you need to use some kind of buffer to read from the stream to be able to detect the end of your messages.