Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Socket Buffer size in C#

Tags:

c#

tcp

sockets

I have a Socket code which is communicating through TCP/IP.The machine to which i am communicating has buffer data in its buffer.At present i am trying to get the buffer data using this code.

byte data = new byte[1024];
int recv = sock.Receive(data);   
stringData = Encoding.ASCII.GetString(data, 0, recv);

But this code retrieves only 11 lines of data whereas more data is there in the machines buffer.Is this because i have used int recv = sock.Receive(data); and data is 1024 ? If yes ,How to get the total buffer size and retrieve it into string.

like image 818
Ram Avatar asked Dec 10 '25 09:12

Ram


1 Answers

If you think you are missing some data, then you need to check recv and almost certainly: loop. Fortunately, ASCII is always single byte - in most other encodings you would also have to worry about receiving partial characters.

A common approach is basically:

int recv;
while((recv = sock.Receive(data)) > 0)
{
    // process recv-many bytes
    // ... stringData = Encoding.ASCII.GetString(data, 0, recv);
}

Keep in mind that there is no guarantee that stringData will be any particular entire unit of work; what you send is not always what you receive, and that could be a single character, 14 lines, or the second half of one word and the first half of another. You generally need to maintain your own back-buffer of received data until you have a complete logical frame to process.

Note, however, Receive always tries to return something (at least one byte), unless the inbound stream has closed - and will block to do so. If this is a problem, you may need to check the available buffer (sock.Available) to decide whether to do synchronous versus asynchronous receive (i.e. read synchronously while data is available, otherwise request an asynchronous read).

like image 132
Marc Gravell Avatar answered Dec 11 '25 23:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!