From a9d391f90848b1829e26fce3220b2ee01d018a1e Mon Sep 17 00:00:00 2001 From: Nick Proud Date: Sat, 15 Jul 2023 20:10:54 +0100 Subject: [PATCH] Added check in channel loop to see if client had disconnected --- Channel.cs | 32 ++++++++++++++++++++++---------- EasyTCP.csproj | 2 +- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/Channel.cs b/Channel.cs index 22ef955..7090350 100644 --- a/Channel.cs +++ b/Channel.cs @@ -38,20 +38,26 @@ public void Open(TcpClient client) while(isOpen) { - while ((position = stream.Read(buffer, 0, buffer.Length)) != 0 && isOpen) + if (clientDisconnected()) { - data = Encoding.UTF8.GetString(buffer, 0, position); - var args = new DataReceivedArgs() + Close(); + } + else + { + while ((position = stream.Read(buffer, 0, buffer.Length)) != 0 && isOpen) { - Message = data, - ConnectionId = Id, - ThisChannel = this - }; + data = Encoding.UTF8.GetString(buffer, 0, position); + var args = new DataReceivedArgs() + { + Message = data, + ConnectionId = Id, + ThisChannel = this + }; - thisServer.OnDataIn(args); - if(!isOpen) { break; } + thisServer.OnDataIn(args); + if(!isOpen) { break; } + } } - } } } @@ -62,6 +68,7 @@ public void Send(string message) stream.Write(data, 0, data.Length); } + public void Close() { Dispose(false); @@ -88,5 +95,10 @@ public void Dispose() Dispose(disposing: true); GC.SuppressFinalize(this); } + + private bool clientDisconnected() + { + return (thisClient.Client.Available == 0 && thisClient.Client.Poll(1, SelectMode.SelectRead)); + } } } diff --git a/EasyTCP.csproj b/EasyTCP.csproj index cb63190..dbc1517 100644 --- a/EasyTCP.csproj +++ b/EasyTCP.csproj @@ -1,7 +1,7 @@ - netcoreapp3.1 + net6.0