My scenario: I have an async tcp server which accepts connections,and upon requests it responses with this method:
private void SendMessage(Client client, string message)
{
var buffer = Encoding.UTF8.GetBytes(message);
try
{
client.TCPClient.GetStream().Write(buffer, 0, buffer.Length);
}
catch (Exception ex) when (ex is InvalidOperationException || ex is System.IO.IOException)
{
RemoveClient(client);
Task exceptionHandler = Program.ExceptionHandler.Server(ex);
}
}
And I have a client application which receives data with this method:
private string GetMessage()
{
StringBuilder returndata = new StringBuilder();
NetworkStream clientStream = this.tcpClient.GetStream();
var sr = new StreamReader(clientStream, Encoding.UTF8);
int value;
while (sr.Peek() >= 0 || clientStream.DataAvailable)
{
value = sr.Read();
returndata.Append((char)value);
}
return returndata.ToString();
}
Mostly I send objects serialized with JSON,and it has worked fine until now. When I restart the client it grabs data from the server, but sometimes only a part of it arrives and the application crashes with ArgumentException at JSON deserialize. It's strange that when it happens (randomly) sr.Peek() = -1 but clientStream.DataAvailable = true
Another information is that always when it crashes the readed message is the same.
Anyone could help me what could cause that sometimes I got only a part of the message not all?