So I'm connecting to a proxy server with my C# program using the TcpClient class. I establish the connection and just keep reading from the server into the buffer with the ReadAsync method. But when the proxys device disconnects, it looks like the ReadAsync method goes into a loop and no further code is being processed. Funny thing is, no exception is thrown and the Task still continues to work (putting an await at the Listen() call prevents further execution, even when the device is disconnected).
Code:
public async Task Listen()
{
try
{
await server.ConnectAsync(ServerIP, ServerPort);
if (server.Connected)
{
using (NetworkStream stream = server.GetStream())
{
while (server.Connected)
{
try
{
byte[] buffer = new byte[server.ReceiveBufferSize];
int length = await stream.ReadAsync(buffer, 0, buffer.Length);
}
catch(Exception e)
{
server.Close();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
server.Close();
}
}
Does anybody have any idea how to detect when the device is disconnected, so I could handle it further? The proxy server does not shut down, it just stops sending data.
question from:
https://stackoverflow.com/questions/65903354/readasync-stops-code-execution-no-exception-is-thrown-and-task-is-still-running 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…