-
-
Save terrajobst/8e077db206883ca156dfdb7643969c76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async Task ProcessLinesAsync(NetworkStream stream) | |
{ | |
var buffer = new byte[1024]; | |
var bytesBuffered = 0; | |
var bytesConsumed = 0; | |
while (true) | |
{ | |
var bytesRead = await stream.ReadAsync(buffer, bytesBuffered, buffer.Length - bytesBuffered); | |
if (bytesRead == 0) | |
{ | |
// EOF | |
break; | |
} | |
// Keep track of the amount of buffered bytes | |
bytesBuffered += bytesRead; | |
var linePosition = -1; | |
do | |
{ | |
// Look for a EOL in the buffered data | |
linePosition = Array.IndexOf(buffer, (byte)'\n', bytesConsumed, bytesBuffered - bytesConsumed); | |
if (linePosition >= 0) | |
{ | |
// Calculate the length of the line based on the offset | |
var lineLength = linePosition - bytesConsumed; | |
// Process the line | |
ProcessLine(buffer, bytesConsumed, lineLength); | |
// Move the bytesConsumed to skip past the line we consumed (including \n) | |
bytesConsumed += lineLength + 1; | |
} | |
} | |
while (linePosition >= 0); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment