diff --git a/AsyncTcpClient/AsyncTcpClient.cs b/AsyncTcpClient/AsyncTcpClient.cs
index f5c3f57..5db1537 100644
--- a/AsyncTcpClient/AsyncTcpClient.cs
+++ b/AsyncTcpClient/AsyncTcpClient.cs
@@ -234,11 +234,16 @@ public async Task RunAsync()
Message?.Invoke(this, new AsyncTcpEventArgs("Connection reset remotely", ex));
readLength = -2;
}
+ catch(Exception ex)
+ {
+ Message?.Invoke(this, new AsyncTcpEventArgs("Read from stream failed", ex));
+ readLength = -3;
+ }
if (readLength <= 0)
{
if (readLength == 0)
{
- Message?.Invoke(this, new AsyncTcpEventArgs("Connection closed remotely"));
+ Message?.Invoke(this, new AsyncTcpEventArgs("Connection closed gracefully"));
}
closedTcs.TrySetResult(true);
OnClosed(readLength != -1);
@@ -263,14 +268,27 @@ public async Task RunAsync()
}
///
- /// Closes the socket connection normally. This does not release the resources used by the
+ /// Closes the socket connection normally. Switch off AutoReconnect. This does not release the resources used by the
/// .
///
public void Disconnect()
{
+ AutoReconnect = false;
+ tcpClient.Client.Disconnect(false);
+ }
+
+
+ ///
+ /// Closes the socket connection normally and try to connect again. This does not release the resources used by the
+ /// .
+ ///
+ public void DisconnectAndReconnect()
+ {
+ AutoReconnect = true;
tcpClient.Client.Disconnect(false);
}
+
///
/// Releases the managed and unmanaged resources used by the .
/// Closes the connection to the remote host and disabled automatic reconnecting.
diff --git a/AsyncTcpClientDemo/Program.cs b/AsyncTcpClientDemo/Program.cs
index d559647..5d3d53d 100644
--- a/AsyncTcpClientDemo/Program.cs
+++ b/AsyncTcpClientDemo/Program.cs
@@ -94,9 +94,9 @@ private async Task RunAsync2()
var client = new AsyncTcpClient
{
- IPAddress = IPAddress.IPv6Loopback,
+ IPAddress = IPAddress.Loopback,
Port = port,
- //AutoReconnect = true,
+ AutoReconnect = true,
ConnectedCallback = async (c, isReconnected) =>
{
await c.WaitAsync(); // Wait for server banner
@@ -143,19 +143,29 @@ private async Task RunAsync2()
byte[] bytes = c.ByteBuffer.Dequeue(count);
string message = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
Console.WriteLine("Client: received: " + message);
+
+ if (message == "close")
+ c.Disconnect();
+
return Task.CompletedTask;
}
};
client.Message += (s, a) => Console.WriteLine("Client: " + a.Message);
var clientTask = client.RunAsync();
- await Task.Delay(10 * 1000);
- Console.WriteLine("Program: stopping server");
- server.Stop(true);
- await serverTask;
- client.Dispose();
+ // Setup 1
+ //await Task.Delay(10 * 1000);
+ //Console.WriteLine("Program: stopping server");
+ //server.Stop(true);
+ //await serverTask;
+ //client.Disconnect();
+ //await clientTask;
+
+
+ // Setup 2
await clientTask;
+ client.Dispose();
}
}
}