Regarding Callback method used for BeginReceive method

994 views Asked by At

Following is the callback method that I use in my socket programming at client side for async receiving of data from server:-

Public Sub Connect()    
    m_clientSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
    m_clientSocket.Connect(Ip, PortNo)
    If (m_clientSocket.Connected) Then       
        m_clientSocket.BeginReceive(dataBuffer, 0,dataBuffer.Length SocketFlags.None, New AsyncCallback(AddressOf OnDataReceived), m_clientSocket)     //here I connect the callback OnDataRecieved
    End If    
End Sub    

Public Sub OnDataRecieved(ByVal async As IAsyncResult)    
    Dim Recieved_Size As Integer = m_clientSocket.EndReceive(async)  
    ' rest of the code ...    
End Sub

What my doubt is that when inside "OnDataReceived method" "Received_Size" = 0, should I conclude that the socket has got disconnected? If not, then under what cases should Received_Size be = 0 ?

Why I am asking is that whenever the connected server gets disconnected then "OnDataReceived" method gets called and the resulting "Received_Size" is = 0. But it should be called only when there is some data to be read for the socket, not when connect/disconnect happens, right?

I would really appreciate anyone who would clarify my doubt.

1

There are 1 answers

1
Gideon Engelberth On

From MSDN (emphasis mine):

If the remote host shuts down the Socket connection with the Shutdown method, and all available data has been received, the EndReceive method will complete immediately and return zero bytes.

You have a streaming socket, so this is signaling a disconnect. I suspect that this happens to allow each call to BeginReceive to be matched with a call to EndReceive.