Private Sub DoRead(ByVal ar As IAsyncResult)
Dim intCount As Integer
Try
intCount = _Client.EndReceive(ar)
If intCount < 1 Then
Me.Close()
ReDim _byteBuffer(1024)
RaiseEvent Disconnected(Me)
Exit Sub
End If
AddToBuffer(_byteBuffer, intCount)
'BuildString(_byteBuffer, 0, intCount)
Array.Clear(_byteBuffer, 0, intCount)
_Client.BeginReceive(_byteBuffer, 0, 1024, SocketFlags.None, _
AddressOf DoRead, Nothing)
Catch ex As Exception
Me.Close()
ReDim _byteBuffer(1024)
RaiseEvent Disconnected(Me)
End Try
End Sub
Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, _
ByVal count As Integer)
Try
Dim intIndex As Integer
For intIndex = offset To offset + count - 1
If Bytes(intIndex) = 10 Then
_sBuffer &= vbLf
Else
_sBuffer &= ChrW(Bytes(intIndex))
End If
Next
If _sBuffer.IndexOf(vbCrLf) <> -1 Then
RaiseEvent DataArrival(Me, count)
_byteBuffer.SetValue(_byteBuffer, 0, _byteBuffer.Length)
End If
Catch ex As Exception
RaiseEvent HandleError(Me, ex.Message, ex.TargetSite.Name, _
ex.ToString)
End Try
End Sub
Private Sub AddToBuffer(ByVal bytes() As Byte, ByVal count As Integer)
Dim curUB As Integer
If Not _buffer Is Nothing Then curUB = UBound(_buffer) Else curUB = -1
Dim newUB As Integer = curUB + count
ReDim Preserve _buffer(newUB)
Array.Copy(bytes, 0, _buffer, curUB + 1, count)
Dim byterm As Byte = 4
Dim idx As Integer = Array.IndexOf(_buffer, byterm)
Dim byObj() As Byte
Dim byTmp() As Byte
While idx <> -1
'found an EOT (end of transmission) marker split it if necessary and
'put it in the buffer to get - call DataArrival
Dim ln As Integer = _buffer.Length - (idx + 1)
ReDim byObj(idx - 1)
ReDim byTmp(ln - 1)
Array.Copy(_buffer, 0, byObj, 0, idx)
Array.Copy(_buffer, idx + 1, byTmp, 0, ln)
ReDim _buffer(UBound(byTmp))
Array.Copy(byTmp, _buffer, byTmp.Length)
Me._bufferCol.Add(byObj)
RaiseEvent DataArrival(Me, byObj.Length)
idx = Array.IndexOf(_buffer, byterm)
End While
If count < bytes.Length - 1 And _buffer.Length > 0 Then
_bufferCol.Add(_buffer)
RaiseEvent DataArrival(Me, _buffer.Length)
_buffer = Nothing
End If
End Sub
#End Region
End Class
#Region " Enumerations "
Public Enum WinsockStates
Closed = 0
Open = 1
Listening = 2
ConnectionPending = 3
ResolvingHost = 4
HostResolved = 5
Connecting = 6
Connected = 7
Closing = 8
[Error] = 9
'Listening = 1
'Connected = 2
End Enum
#End Region |