I am using vs 2003, below is the callback method for my socket. The way I
understand how all this works is: sockDataArrival gets started as a thread,
and reads from the server using EndReceive. It checks for bytesRead and if
there is nothing left to read, bytesRead should be zero, otherwise, another
thread is started and so on untill all data is read and bytesRead =0. The
problem I am having is that bytesRead never equals 0. In the first part of
the bytesRead if statement this line "RaiseEvent
onDataArrival(StringToBytes(state.sb.ToString), bytesRead) 'debug" just puts
data into a textbox. All my data comes back. Why is bytesRead never 0 ?
The catch expression never gets fired either so I dont think i am running
into a socket error. Can anyone spot something wrong in my code ? I need
to know when all the data has arrived so I can fire off an event and process
the data I am receiving.
Private Sub sockDataArrival(ByVal ar As IAsyncResult)
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim client As Socket = state.workSocket
Dim bytesRead As Integer
Try
bytesRead = client.EndReceive(ar)
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try
Try
Dim Data() As Byte = state.buffer
If bytesRead = 0 Then
'client.Shutdown(SocketShutdown.Both)
'client.Close()
'RaiseEvent onDisconnect()
'Exit Sub
End If
If bytesRead 0 Then
state.sb.Append(Encoding.ASCII.GetString(state.buf fer, 0,
bytesRead))
'state.sb.Append(BytestoString(state.buffer)) 'save data off to the
side
ReDim state.buffer(256) 'clear buffer
'we might not be done so receive again
RaiseEvent onDataArrival(StringToBytes(state.sb.ToString),
bytesRead) 'debug
client.BeginReceive(state.buffer, 0, state.BufferSize, 0, AddressOf
sockDataArrival, state)
Else
'try not to call data arrival until all data comes in
'data could be bigger than buffer
'data could be sent to us in chunks
'data could be smaller than buffer
'state.sb.Append(BytestoString(state.buffer)) 'save data off to the
side
Dim thing As String = state.sb.ToString
Dim thing2 As Byte() = StringToBytes(thing)
RaiseEvent onDataArrival(StringToBytes(state.sb.ToString),
bytesRead) 'should be done
End If
Catch
RaiseEvent onError(Err.Description)
Exit Sub
End Try
End Sub