Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/handling socket exception on send data #33

Merged
merged 5 commits into from
Jan 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@
<ItemGroup Label="Code Analyzers">
<PackageReference Include="AsyncFixer" Version="1.6.0" PrivateAssets="All" />
<PackageReference Include="Asyncify" Version="0.9.7" PrivateAssets="All" />
<PackageReference Include="Meziantou.Analyzer" Version="2.0.118" PrivateAssets="All" />
<PackageReference Include="Meziantou.Analyzer" Version="2.0.138" PrivateAssets="All" />
<PackageReference Include="SecurityCodeScan.VS2019" Version="5.6.7" PrivateAssets="All" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435" PrivateAssets="All" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.14.0.81108" PrivateAssets="All" />
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.17.0.82934" PrivateAssets="All" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Atc" Version="2.0.395" />
<PackageReference Include="Atc" Version="2.0.422" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Atc" Version="2.0.395" />
<PackageReference Include="Atc" Version="2.0.422" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/Atc.Network/Atc.Network.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Atc" Version="2.0.395" />
<PackageReference Include="Atc" Version="2.0.422" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>

Expand Down
14 changes: 10 additions & 4 deletions src/Atc.Network/LoggingEventIdConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@ internal static class TcpClient
public const int Disconnected = 10009;

public const int DataSendingByteLength = 10010;
public const int DataReceivedByteLength = 10011;
public const int DataReceiveTimeout = 10012;
public const int DataReceiveNoData = 10013;
public const int DataReceiveError = 10014;
public const int DataSendingSocketError = 10011;
public const int DataSendingError = 10012;
public const int DataReceivedByteLength = 10013;
public const int DataReceiveTimeout = 10014;
public const int DataReceiveNoData = 10015;
public const int DataReceiveError = 10016;
}

internal static class TcpServer
Expand All @@ -41,11 +43,15 @@ internal static class UdpClient
public const int ClientNotConnected = 10207;
public const int Disconnecting = 10208;
public const int Disconnected = 10209;
public const int DataSendingSocketError = 10210;
public const int DataSendingError = 10211;
}

internal static class UdpServer
{
public const int DataReceivedByteLength = 10311;
public const int NotRunning = 10320;
public const int DataSendingSocketError = 10321;
public const int DataSendingError = 10322;
}
}
37 changes: 31 additions & 6 deletions src/Atc.Network/Tcp/TcpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -280,8 +280,33 @@ public async Task Send(

LogDataSendingByteLength(data.Length);

await networkStream!.WriteAsync(data.AsMemory(0, data.Length), cancellationToken);
await networkStream.FlushAsync(cancellationToken);
await SyncLock.WaitAsync(cancellationToken);
var disconnectedDueToException = false;

try
{
await networkStream!.WriteAsync(data.AsMemory(0, data.Length), cancellationToken);
await networkStream.FlushAsync(cancellationToken);
}
catch (SocketException ex)
{
LogDataSendingSocketError(ex.SocketErrorCode.ToString(), ex.Message);
disconnectedDueToException = true;
}
catch (Exception ex)
{
LogDataSendingError(ex.Message);
disconnectedDueToException = true;
}
finally
{
SyncLock.Release();
}

if (disconnectedDueToException)
{
await DoDisconnect(raiseEventsAndLog: true, dispose: true);
}
}

/// <summary>
Expand Down Expand Up @@ -497,10 +522,10 @@ private async Task SetConnected(
bool raiseEvents,
CancellationToken cancellationToken = default)
{
await SyncLock.WaitAsync(cancellationToken);

try
{
await SyncLock.WaitAsync(cancellationToken);

if (IsConnected)
{
return;
Expand All @@ -523,10 +548,10 @@ private async Task SetDisconnected(
bool dispose,
CancellationToken cancellationToken = default)
{
await SyncLock.WaitAsync(cancellationToken);

try
{
await SyncLock.WaitAsync(cancellationToken);

if (!IsConnected)
{
return;
Expand Down
15 changes: 15 additions & 0 deletions src/Atc.Network/Tcp/TcpClientLoggerMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ private partial void LogDisconnected(
private partial void LogDataSendingByteLength(
int byteLength);

[LoggerMessage(
EventId = LoggingEventIdConstants.TcpClient.DataSendingSocketError,
Level = LogLevel.Error,
Message = "Received error when sending data - {socketError}: {errorMessage}.")]
private partial void LogDataSendingSocketError(
string socketError,
string errorMessage);

[LoggerMessage(
EventId = LoggingEventIdConstants.TcpClient.DataSendingError,
Level = LogLevel.Error,
Message = "Received error when sending data: {errorMessage}.")]
private partial void LogDataSendingError(
string errorMessage);

[LoggerMessage(
EventId = LoggingEventIdConstants.TcpClient.DataReceivedByteLength,
Level = LogLevel.Trace,
Expand Down
37 changes: 31 additions & 6 deletions src/Atc.Network/Udp/UdpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,33 @@ public async Task Send(
TerminationHelper.AppendTerminationBytesIfNeeded(ref data, terminationType);

var buffer = new ArraySegment<byte>(data);
await socket!.SendToAsync(buffer, SocketFlags.None, RemoteEndPoint, cancellationToken);
await Task.Delay(TimeSpan.FromMilliseconds(1), cancellationToken);
await SyncLock.WaitAsync(cancellationToken);
var disconnectedDueToException = false;

try
{
await socket!.SendToAsync(buffer, SocketFlags.None, RemoteEndPoint, cancellationToken);
await Task.Delay(TimeSpan.FromMilliseconds(1), cancellationToken);
}
catch (SocketException ex)
{
LogDataSendingSocketError(ex.SocketErrorCode.ToString(), ex.Message);
disconnectedDueToException = true;
}
catch (Exception ex)
{
LogDataSendingError(ex.Message);
disconnectedDueToException = true;
}
finally
{
SyncLock.Release();
}

if (disconnectedDueToException)
{
await DoDisconnect(raiseEventsAndLog: true);
}
}

/// <summary>
Expand Down Expand Up @@ -351,10 +376,10 @@ private async Task SetConnected(
bool raiseEvents,
CancellationToken cancellationToken = default)
{
await SyncLock.WaitAsync(cancellationToken);

try
{
await SyncLock.WaitAsync(cancellationToken);

if (IsConnected)
{
return;
Expand All @@ -376,10 +401,10 @@ private async Task SetDisconnected(
bool raiseEvents = true,
CancellationToken cancellationToken = default)
{
await SyncLock.WaitAsync(cancellationToken);

try
{
await SyncLock.WaitAsync(cancellationToken);

if (!IsConnected)
{
return;
Expand Down
15 changes: 15 additions & 0 deletions src/Atc.Network/Udp/UdpClientLoggerMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,19 @@ private partial void LogDisconnecting(
private partial void LogDisconnected(
string ipAddressOrHostName,
int port);

[LoggerMessage(
EventId = LoggingEventIdConstants.UdpClient.DataSendingSocketError,
Level = LogLevel.Error,
Message = "Received error when sending data - {socketError}: {errorMessage}.")]
private partial void LogDataSendingSocketError(
string socketError,
string errorMessage);

[LoggerMessage(
EventId = LoggingEventIdConstants.UdpClient.DataSendingError,
Level = LogLevel.Error,
Message = "Received error when sending data: {errorMessage}.")]
private partial void LogDataSendingError(
string errorMessage);
}
14 changes: 13 additions & 1 deletion src/Atc.Network/Udp/UdpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,19 @@ public async Task Send(
AppendTerminationBytesIfNeeded(ref data, terminationType);

var buffer = new ArraySegment<byte>(data);
await socket!.SendToAsync(buffer, SocketFlags.None, recipient, cancellationToken);

try
{
await socket!.SendToAsync(buffer, SocketFlags.None, recipient, cancellationToken);
}
catch (SocketException ex)
{
LogDataSendingSocketError(ex.SocketErrorCode.ToString(), ex.Message);
}
catch (Exception ex)
{
LogDataSendingError(ex.Message);
}
}

/// <summary>
Expand Down
15 changes: 15 additions & 0 deletions src/Atc.Network/Udp/UdpServerLoggerMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,19 @@ public partial class UdpServer
Message = "Received '{byteLength}' bytes.")]
private partial void LogDataReceived(
int byteLength);

[LoggerMessage(
EventId = LoggingEventIdConstants.UdpServer.DataSendingSocketError,
Level = LogLevel.Error,
Message = "Received error when sending data - {socketError}: {errorMessage}.")]
private partial void LogDataSendingSocketError(
string socketError,
string errorMessage);

[LoggerMessage(
EventId = LoggingEventIdConstants.UdpServer.DataSendingError,
Level = LogLevel.Error,
Message = "Received error when sending data: {errorMessage}.")]
private partial void LogDataSendingError(
string errorMessage);
}
6 changes: 3 additions & 3 deletions test/Atc.Network.Test/Atc.Network.Test.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Atc.XUnit" Version="2.0.395" />
<PackageReference Include="Atc.XUnit" Version="2.0.422" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.6.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.4">
<PackageReference Include="xunit" Version="2.6.6" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
Expand Down
Loading