From bc64da55046df91d56b2c23ff97341f70aef85a1 Mon Sep 17 00:00:00 2001 From: Lucas Rodrigues Date: Wed, 9 Nov 2022 08:52:23 -0300 Subject: [PATCH] notify client when connection gets started or interrupted --- SimpleTCP/SimpleTcpClient.cs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/SimpleTCP/SimpleTcpClient.cs b/SimpleTCP/SimpleTcpClient.cs index 5c66a93..986983c 100644 --- a/SimpleTCP/SimpleTcpClient.cs +++ b/SimpleTCP/SimpleTcpClient.cs @@ -26,7 +26,19 @@ public SimpleTcpClient() public event EventHandler DelimiterDataReceived; public event EventHandler DataReceived; + public event EventHandler ConnectionInterrupted; + public event EventHandler ConnectionStarted; + public bool IsConnected => _client?.Connected ?? false; + + private void NotifyConnectionInterrupted(TcpClient client, byte[] msg) + { + ConnectionInterrupted?.Invoke(this, EventArgs.Empty); + } + private void NotifyConnectionStarted(TcpClient client, byte[] msg) + { + ConnectionStarted?.Invoke(this, EventArgs.Empty); + } internal bool QueueStop { get; set; } internal int ReadLoopIntervalMs { get; set; } public bool AutoTrimStrings { get; set; } @@ -58,6 +70,8 @@ private void StartRxThread() public SimpleTcpClient Disconnect() { if (_client == null) { return this; } + NotifyConnectionInterrupted(_client, null); + flagNotifiedStarted = false; _client.Close(); _client = null; return this; @@ -84,10 +98,25 @@ private void ListenerLoop(object state) _rxThread = null; } + + private bool flagNotifiedStarted = false; private void RunLoopStep() { if (_client == null) { return; } - if (_client.Connected == false) { return; } + if (_client.Connected == false) + { + NotifyConnectionInterrupted(_client, null); + flagNotifiedStarted = false; + return; + } + else + { + if (!flagNotifiedStarted) + { + NotifyConnectionStarted(_client, null); + flagNotifiedStarted = true; + } + } var delimiter = this.Delimiter; var c = _client;