Reputation: 73
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.
Upvotes: 1
Views: 874
Reputation: 456507
This can happen if the proxy side of the connection is clamped shut - i.e., closed without sending your application a packet indicating it is closed. This leaves the connection in a half-open state.
You need to design your application to handle this. The best approaches are to have a "heartbeat" or "keepalive" packet that is periodically sent by each side. If your proxy protocol supports that, then that would be ideal. Otherwise, you'll probably need to use a timeout; just set a timer (one per connection), reset it each time you receive data, and close your side of the socket when the timer fires.
Upvotes: 6