var buffer = new byte[short.MaxValue];
var splitString = new string[] {"\r\n"};
while (_tcpClient.Connected)
{
if (!_networkStream.CanRead || !_networkStream.DataAvailable)
continue;
var bytesRead = _networkStream.Read(buffer, 0, buffer.Length);
var stringBuffer = Encoding.ASCII.GetString(buffer, 0, bytesRead);
var messages =
stringBuffer.Split(splitString, StringSplitOptions.RemoveEmptyEntries);
foreach (var message in messages)
{
if (MessageReceived != null)
{
MessageReceived(this, new SimpleTextClientEventArgs(message));
}
}
}
Problem is that even with a buffer as big as short.MaxValue, you can actually fill the buffer. When you split the string that you create from the buffer, the last string gets chomped, and the rest of it comes with the next read.
I was thinking of creating a buffer large enough for a single line (which according to RFC2812 is 512 chars), extracting a substring up until the first "\r\n", then array-copying the rest of the data to the beginning of the buffer and using the offset parameter to read more data onto the end of the data that wasn't extracted last iteration. Sorry if that was hard to follow...
Is that the best solution, or am I missing the obvious here?