I'm writing in VB.NET, using VS Community 2013. I don't know much about this language. I have managed to make my code work, but I suspect it is possible to improve the code a lot.
This code extracts packets from some data I've received using TcpClient
.
Private inbuf(10000) As Byte
Private inoff As Integer
Private Sub ProcessBuffer
' Buffer may contain multiple packets, delimited by a newline
Do While 1
Dim newline As Byte = 10
Dim newline_index = System.Array.IndexOf(Of Byte)([inbuf], newline) ' I think this is zero-based index
Dim Data As String = Nothing ' if I leave this initializer out then Data seems to retain its value for next loop iteration
If (newline_index >= 0 AndAlso newline_index < inoff) Then ' packet found
Data = Encoding.ASCII.GetString(inbuf, 0, newline_index)
inbuf = inbuf.Skip(newline_index + 1).ToArray()
ReDim Preserve inbuf(10000) ' the Skip shortened the array
inoff = inoff - (newline_index + 1)
If inoff < 0 Then inoff = 0 ' shouldn't happen but seems to happen sometimes?
End If
' If we did not find a newline (or the input was empty string), it means we need to wait for more input
If String.IsNullOrEmpty(Data) Then
Return
End If
' Process the response string
handle_packet(Data)
Loop
End Sub
IASyncResult
pattern, is it an option for you to use the newer Async methods (ReadAsync
, etc.)? .NET 4.5+ would be required. \$\endgroup\$ReadAsync
in this situation; I want my UI to remain responsive while waiting for data and could not find any code examples along those lines (all the examples show executing some other statements simultaneously with the async call, but then blocking for the async call to complete once those other statements are finished) \$\endgroup\$