Socket.BeginReceive Question

  • Thread starter Thread starter Mike Hildner
  • Start date Start date
M

Mike Hildner

In all the examples that come with VS, the callback method passed to
BeginReceive look something like:

Dim read As Integer = s.EndReceive(ar)

If read > 0 Then
so.sb.Append(Encoding.ASCII.GetString(so.buffer, 0, read))
s.BeginReceive(so.buffer, 0, StateObject.BUFFER_SIZE, 0, New
AsyncCallback(AddressOf Async_Send_Receive.Read_Callback), so)
Else
' All the data has been read.

So some data comes over, you grab it, then do BeginReceive again in case
there's more data in the buffer (at least in my understanding). But the
documentation says that EndReceive will block until some data is there or
there is a Socket Exception.

Are all these examples incorrect in coding that if the bytes read = 0 then
all the data has been read? The only time my code gets there is when there
is an error.

Just hoping for some clarification,
Mike
 
You will only get zero bytes read if there was an error condition, including
if the peer socket was closed, so maybe in their example they mean the peer
socket connects, sends one message then close. In this case the last call to
EndReceive will read zero bytes. As long as the peer socket stays connected
and no error occurs, even if no data is sent from it ever, the read will
never return zero bytes. So the comment in the example should have said "All
data has been read Or error condition". Must have been a newby that wrote
the example.
 
Thank you for the clarification, Chris. I can't recall reading that they
expect the client to send then close the socket, but that seems what that
code is expecting. Much appreciated.

Regards,
Mike
 
Back
Top