Skip to content

Commit

Permalink
Dictionary update (#2)
Browse files Browse the repository at this point in the history
* More robust disconnection

* Update TcpAdapter.cs

* Update TcpConnection.cs

* Update TcpAdapter.csproj

* Update TcpAdapter.csproj

* Update TcpAdapter.csproj
  • Loading branch information
tbm0115 authored Jul 31, 2023
1 parent 5ca26a9 commit 2e7cbab
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 13 deletions.
12 changes: 8 additions & 4 deletions Mtconnect.TcpAdapter/TcpAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ private async Task ListenForClients()

if (!_clients.ContainsKey(client.ClientId))
{
_logger?.LogInformation("New client connection '{ClientId}'", client.ClientId);
_logger?.LogInformation("New client connection '{ClientId}' ({ActiveConnections}/{MaxConnections})", client.ClientId, _clients.Count, MaxConnections);
if (_clients.TryAdd(client.ClientId, client))
{
client.OnDisconnected += Client_OnConnectionDisconnected;
Expand Down Expand Up @@ -320,25 +320,29 @@ private void Client_OnConnectionDisconnected(TcpConnection connection, Exception
{
if (!_clients.ContainsKey(connection.ClientId))
{
_logger?.LogWarning("Client '{ClientId}' is not tracked", connection.ClientId);
_logger?.LogWarning("Client '{ClientId}' could not be disconnected because it is not currently tracked", connection.ClientId);
return;
}

lock (_clients)
{
if (ex == null)
{
_logger?.LogInformation("Client disconnected '{ClientId}'", connection.ClientId);
_logger?.LogDebug("Client disconnecting '{ClientId}'", connection.ClientId);
} else
{
_logger?.LogError("Client '{ClientId}' disconnected due to error: \r\n\t{Error}", connection.ClientId, ex);
_logger?.LogError("Client '{ClientId}' disconnecting due to error: \r\n\t{Error}", connection.ClientId, ex);
}
if (_clients.TryRemove(connection.ClientId, out TcpConnection client))
{
_logger?.LogInformation("Client '{ClientId}' disconnected", connection.ClientId);
if (_clients.Count == 0)
{
_logger?.LogInformation("No clients connected");
}
} else
{
_logger?.LogWarning("Client '{ClientId}' failed to disconnect and may still linger", connection.ClientId);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions Mtconnect.TcpAdapter/TcpAdapter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
<RepositoryType>git</RepositoryType>
<PackageTags>Mtconnect;Adapter;TCP;TAMS;</PackageTags>
<PackageReleaseNotes>Updated to latest AdapterSDK. Support for reference Agent SHDR commands.</PackageReleaseNotes>
<Version>2.0.3</Version>
<Version>2.0.4</Version>
<IncludeSymbols>True</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -52,7 +52,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Mtconnect.AdapterSdk" Version="2.0.2" />
<PackageReference Include="Mtconnect.AdapterSdk" Version="2.0.3" />
</ItemGroup>

<ItemGroup>
Expand Down
43 changes: 36 additions & 7 deletions Mtconnect.TcpAdapter/TcpConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Net.Sockets;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Mtconnect
Expand All @@ -14,6 +15,7 @@ namespace Mtconnect
public class TcpConnection : IDisposable
{
private bool _disposing { get; set; } = false;
private bool _disconnecting { get; set; } = false;

/// <summary>
/// An event that fires when the underlying client stream is opened and connected.
Expand Down Expand Up @@ -53,6 +55,7 @@ public class TcpConnection : IDisposable
private TcpClient _client { get; set; }

private Task _receiverThread;
private CancellationTokenSource _receiverSource;

/// <summary>
/// Reference to the underlying client stream. Note, only available between <see cref="Connect"/> and <see cref="Disconnect"/> calls.
Expand Down Expand Up @@ -82,9 +85,10 @@ public void Connect()

_stream = _client.GetStream();

_receiverSource = new CancellationTokenSource();
_receiverThread = Task.Factory.StartNew(
receive,
default,
_receiverSource.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default
);
Expand All @@ -97,15 +101,40 @@ public void Connect()
/// </summary>
public void Disconnect(Exception ex = null)
{
_disconnecting = true;
if (_stream == null) return;

_receiverThread?.Dispose();
try
{
_receiverSource?.Cancel();
_receiverSource?.Dispose();
_receiverSource = null;
}
catch (Exception cancellationException)
{
}

try
{
_receiverThread?.Dispose();
_receiverThread = null;
}
catch (Exception receiverException)
{
}

_stream?.Close();
_stream?.Dispose();
_stream = null;
try
{
_stream?.Close();
_stream?.Dispose();
_stream = null;
}
catch (Exception streamException)
{
}

if (!_disposing && OnDisconnected != null) OnDisconnected(this, ex);
_disconnecting = false;
}

/// <summary>
Expand Down Expand Up @@ -150,7 +179,7 @@ private async Task receive()

ArrayList readList = new ArrayList();

while (_client.Connected)
while (_client.Connected && !_disconnecting)
{
if (!_stream.DataAvailable)
{
Expand Down Expand Up @@ -205,8 +234,8 @@ private async Task receive()
public void Dispose()
{
_disposing = true;
_client?.Dispose();
Disconnect();
_client?.Dispose();
_disposing = false;
}
}
Expand Down

0 comments on commit 2e7cbab

Please sign in to comment.