EDIT: I understand the issue but need a code example to show how to solve it.
I would like for my client to reconnect automatically if it becomes disconnected but it appears TcpClient.Connected
is not reliable for it. I've read that you need to send data for the class to change that flag. Is there a better way to handle to problem?
//Method to handle reading data from buffer and deserializing
public static async Task<Message> ReadMessageAsync(this TcpClient client)
{
if (client.Connected && client.Available > 0)
{
int totalBytesRead = 0;
var data = new byte[client.Available];
while (totalBytesRead < client.Available)
{
totalBytesRead += await client.GetStream().ReadAsync(data, 0, client.Available);
}
return BinarySerializer.DeserializeMessage(data) as Message;
}
return null;
}
public async Task Start()
{
ConnectToServer();
while (_isRunning)
{
// Reconnect to server if needed.
if (!_tcpClient.Connected)
{
ConnectToServer();
}
// Wait for data
var data = await _tcpClient.ReadMessageAsync();
HandleData(data);
}
}