Private Sub ReceiveCallBack(ByVal ar As IAsyncResult) '--Retreive array of bytes Dim bytes() As Byte = (ar.AsyncState) Try '--Get number of bytes received and also clean up resources that was used from beginReceive Dim numBytes As Int32 = _mySocket.EndReceive(ar) '--Did we receive anything? If numBytes > 0 Then '--Resize the array to match the number of bytes received. Also keep the current data ReDim Preserve bytes(numBytes - 1) Dim received As String = _ascii.GetString(bytes) '--Now we need to raise the received event. ' args() is used to pass an argument from this thread to the synchronized container's ui thread. Dim args(0) As Object '--Create a new delegate for the OnReceive event Dim d As New RaiseReceiveEvent(AddressOf OnReceive) If _lineMode = True Then '--Yes, split the string into an array based on the EOL character Dim sep() As Char = {EOLChar} Dim lines() As String = received.Split(sep) Dim i As Int32 '--Raise the received event once for every line of text! For i = 0 To lines.Length - 1 If i = lines.Length - 1 Then args(0) = lines(i) Else args(0) = lines(i) & EOLChar End If '--Invoke the private delegate from the thread. d.Invoke(args(0)) Next i = Nothing Else '--Not line mode. Pass the entire string at once with only one event args(0) = received '--Invoke the private delegate from the thread. d.Invoke(args(0)) End If received = Nothing End If Catch ex As Exception '--Raise the exception event Dim args() As Object = {ex} 'Dim d As New RaiseExceptionEvent(AddressOf OnExcpetion) '_syncObject.Invoke(d, args) 'd.Invoke(args(0)) '--If not connected, raise the connected event If IsConnected() = False Then args(0) = False Dim dl As New RaiseConnectedEvent(AddressOf OnConnected) dl.Invoke(args(0)) bytes = Nothing ar = Nothing ' _mySocket.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, AddressOf ReceiveCallBack, bytes) End If End Try '--Are we stil conncted? If IsConnected() = False Then '--Raise the connect event Dim args() As Object = {False} Dim d As New RaiseConnectedEvent(AddressOf OnConnected) d.Invoke(False) bytes = Nothing ar = Nothing args = Nothing Else '--Yes, then resize bytes to packet size ReDim bytes(PacketSize - 1) '--Call BeginReceive again, catching any error Try _mySocket.BeginReceive(bytes, 0, bytes.Length, SocketFlags.None, AddressOf ReceiveCallBack, bytes) Catch ex As Exception '--Raise the exception event Dim args() As Object = {ex} Dim d As New RaiseExceptionEvent(AddressOf OnExcpetion) '_syncObject.Invoke(d, args) d.Invoke(args(0)) '--If not connected, raise the connected event If IsConnected() = False Then args(0) = False ' Dim dl As New RaiseConnectedEvent(AddressOf OnConnected) 'dl.Invoke(args(0)) bytes = Nothing ar = Nothing args(0) = Nothing End If End Try End If End Sub
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)