Need help - Socket EndReceive & BeginReceive

M

Marty

Hi,

I have a socket that always seek for incoming data.
Between Point A and Point B, the socket (mySocket is closed and assigned
to nothing in another part of my program (happen when a connection is
broken). So regurlarly when a socket is closed, it create an error
somewhere in this routine, even if I check if the socket is nothing or
not, and connected or not (I also tried to check before doing the
beginreceive)

Do you have an idea to prevent an endreceive or beginreceive error? I
can catch the error, but raising an error is heavy time consuming.

Thanks you very much

Marty

Private Sub checkIncomingData(ByVal ar As IAsyncResult)
Dim BytesRead As Integer
Dim strTempMessage As String
If (Not mySocket Is Nothing) Then
If (mySocket.Connected) Then
BytesRead = mySocket.EndReceive(ar)

'Point A
strTempMessage = Encoding.ASCII.GetString(Buffer, 0, BytesRead)
'Do something with strTempMessage

'Point B
mySocket.BeginReceive(Buffer, 0, READ_BUFFER_SIZE,
SocketFlags.None, AddressOf checkIncomingData, Nothing)

End If
End If
End Sub

'I omitted the try catch code, but all errors are catch in my code.
 
M

Marty

Here is my solution if you had the same problem.

Call mySocket.Shutdown(SocketShutdown.Both)
before doing mySocket.Close()

This will interrupt the mySocket.BeginReceive thread.

I did a couple of connection disconnect test and it work for me, I'll
test more deeply with other use-case.

Have a nice day

Marty
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top