I've been reading the documentation from Microsoft regarding the Asynchronous Socket.Beginreceive method......
According to Microsoft... the following code works....
It's supposed to be re-entrant depending on the bytes received.Code:Private Shared Sub Receive(ByVal client As Socket) ' Create the state object. Dim state As New StateObject state.workSocket = client ' Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) End Sub 'Receive Private Shared Sub ReceiveCallback(ByVal ar As IAsyncResult) ' Retrieve the state object and the client socket ' from the asynchronous state object. Dim state As StateObject = CType(ar.AsyncState, StateObject) Dim client As Socket = state.workSocket ' Read data from the remote device. Dim bytesRead As Integer = client.EndReceive(ar) If bytesRead > 0 Then ' There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)) ' Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) Else ' All the data has arrived; put it in response. If state.sb.Length > 1 Then response = state.sb.ToString() End If ' Signal that all bytes have been received. receiveDone.Set() End If End Sub 'ReceiveCallback
BUT, I'm using the same code with little modifications....and the ReceiveDone.Set NEVER gets called. So my program is blocking while waiting for the Set signal.
I've attached my code below..
What am I doing wrong???Code:Private Sub Receive(ByVal client As Socket) ' Create the state object. Dim state As New StateObject state.workSocket = client ' Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) End Sub 'Receive Private Sub ReceiveCallback(ByVal ar As IAsyncResult) ' Retrieve the state object and the client socket ' from the asynchronous state object. Dim state As StateObject = CType(ar.AsyncState, StateObject) Dim client As Socket = state.workSocket Dim lstrTemp As String ' Read data from the remote device. Dim bytesRead As Integer = client.EndReceive(ar) If bytesRead > 0 Then Try ' There might be more data, so store the data received so far. lstrTemp = Encoding.ASCII.GetString(state.buffer, 0, bytesRead) state.sb.Append(lstrTemp) ' Get the rest of the data. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReceiveCallback), state) Catch lstrTemp = String.Empty End Try Else If state.sb.Length > 1 Then Host_Response(state.sb.ToString) End If ReceiveDone.Set() End If




Reply With Quote