Socket Client - bytesread never reaches zero

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Demosthenes

    #1

    Socket Client - bytesread never reaches zero

    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(S tringToBytes(st ate.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.AsyncS tate, StateObject)
    Dim client As Socket = state.workSocke t
    Dim bytesRead As Integer

    Try
    bytesRead = client.EndRecei ve(ar)
    Catch
    RaiseEvent onError(Err.Des cription)
    Exit Sub
    End Try

    Try
    Dim Data() As Byte = state.buffer
    If bytesRead = 0 Then
    'client.Shutdow n(SocketShutdow n.Both)
    'client.Close()
    'RaiseEvent onDisconnect()
    'Exit Sub
    End If

    If bytesRead 0 Then
    state.sb.Append (Encoding.ASCII .GetString(stat e.buffer, 0,
    bytesRead))

    'state.sb.Appen d(BytestoString (state.buffer)) 'save data off to the
    side
    ReDim state.buffer(25 6) 'clear buffer
    'we might not be done so receive again
    RaiseEvent onDataArrival(S tringToBytes(st ate.sb.ToString ),
    bytesRead) 'debug
    client.BeginRec eive(state.buff er, 0, state.BufferSiz e, 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.Appen d(BytestoString (state.buffer)) 'save data off to the
    side
    Dim thing As String = state.sb.ToStri ng
    Dim thing2 As Byte() = StringToBytes(t hing)
    RaiseEvent onDataArrival(S tringToBytes(st ate.sb.ToString ),
    bytesRead) 'should be done
    End If
    Catch
    RaiseEvent onError(Err.Des cription)
    Exit Sub
    End Try
    End Sub


Working...