1
0
mirror of https://github.com/JKorf/CryptoExchange.Net synced 2025-06-12 02:16:23 +00:00

Fix for socket issues .net framework

This commit is contained in:
Jkorf 2021-10-06 09:12:46 +02:00
parent 4758d348de
commit af6f4d14f6

View File

@ -44,7 +44,7 @@ namespace CryptoExchange.Net.Sockets
/// <summary> /// <summary>
/// Received messages time -> size /// Received messages time -> size
/// </summary> /// </summary>
protected readonly Dictionary<DateTime, int> _receivedMessages; internal readonly List<ReceiveItem> _receivedMessages;
/// <summary> /// <summary>
/// Received messages lock /// Received messages lock
/// </summary> /// </summary>
@ -152,7 +152,7 @@ namespace CryptoExchange.Net.Sockets
if (!_receivedMessages.Any()) if (!_receivedMessages.Any())
return 0; return 0;
return Math.Round(_receivedMessages.Values.Sum(v => v) / 1000 / 3d); return Math.Round(_receivedMessages.Sum(v => v.Bytes) / 1000 / 3d);
} }
} }
} }
@ -215,7 +215,7 @@ namespace CryptoExchange.Net.Sockets
this.headers = headers; this.headers = headers;
_outgoingMessages = new List<DateTime>(); _outgoingMessages = new List<DateTime>();
_receivedMessages = new Dictionary<DateTime, int>(); _receivedMessages = new List<ReceiveItem>();
_sendEvent = new AsyncResetEvent(); _sendEvent = new AsyncResetEvent();
_sendBuffer = new ConcurrentQueue<byte[]>(); _sendBuffer = new ConcurrentQueue<byte[]>();
_ctsSource = new CancellationTokenSource(); _ctsSource = new CancellationTokenSource();
@ -380,6 +380,8 @@ namespace CryptoExchange.Net.Sockets
private async Task SendLoopAsync() private async Task SendLoopAsync()
{ {
_startedSent = true; _startedSent = true;
try
{
while (true) while (true)
{ {
if (_closing) if (_closing)
@ -392,7 +394,7 @@ namespace CryptoExchange.Net.Sockets
while (_sendBuffer.TryDequeue(out var data)) while (_sendBuffer.TryDequeue(out var data))
{ {
if(RatelimitPerSecond != null) if (RatelimitPerSecond != null)
{ {
// Wait for rate limit // Wait for rate limit
DateTime? start = null; DateTime? start = null;
@ -435,6 +437,15 @@ namespace CryptoExchange.Net.Sockets
} }
} }
} }
catch (Exception e)
{
// Because this is running in a separate task and not awaited until the socket gets closed
// any exception here will crash the send processing, but do so silently unless the socket get's stopped.
// Make sure we at least let the owner know there was an error
Handle(errorHandlers, e);
throw;
}
}
/// <summary> /// <summary>
/// Loop for receiving and reassembling data /// Loop for receiving and reassembling data
@ -446,6 +457,8 @@ namespace CryptoExchange.Net.Sockets
var buffer = new ArraySegment<byte>(new byte[65536]); var buffer = new ArraySegment<byte>(new byte[65536]);
var received = 0; var received = 0;
try
{
while (true) while (true)
{ {
if (_closing) if (_closing)
@ -460,8 +473,8 @@ namespace CryptoExchange.Net.Sockets
{ {
receiveResult = await _socket.ReceiveAsync(buffer, _ctsSource.Token).ConfigureAwait(false); receiveResult = await _socket.ReceiveAsync(buffer, _ctsSource.Token).ConfigureAwait(false);
received += receiveResult.Count; received += receiveResult.Count;
lock(_receivedMessagesLock) lock (_receivedMessagesLock)
_receivedMessages.Add(DateTime.UtcNow, receiveResult.Count); _receivedMessages.Add(new ReceiveItem(DateTime.UtcNow, receiveResult.Count));
} }
catch (OperationCanceledException) catch (OperationCanceledException)
{ {
@ -542,6 +555,15 @@ namespace CryptoExchange.Net.Sockets
} }
} }
} }
catch(Exception e)
{
// Because this is running in a separate task and not awaited until the socket gets closed
// any exception here will crash the receive processing, but do so silently unless the socket get's stopped.
// Make sure we at least let the owner know there was an error
Handle(errorHandlers, e);
throw;
}
}
/// <summary> /// <summary>
/// Handles the message /// Handles the message
@ -604,6 +626,8 @@ namespace CryptoExchange.Net.Sockets
protected async Task CheckTimeoutAsync() protected async Task CheckTimeoutAsync()
{ {
log.Write(LogLevel.Debug, $"Socket {Id} Starting task checking for no data received for {Timeout}"); log.Write(LogLevel.Debug, $"Socket {Id} Starting task checking for no data received for {Timeout}");
try
{
while (true) while (true)
{ {
if (_closing) if (_closing)
@ -626,6 +650,15 @@ namespace CryptoExchange.Net.Sockets
} }
} }
} }
catch (Exception e)
{
// Because this is running in a separate task and not awaited until the socket gets closed
// any exception here will stop the timeout checking, but do so silently unless the socket get's stopped.
// Make sure we at least let the owner know there was an error
Handle(errorHandlers, e);
throw;
}
}
/// <summary> /// <summary>
/// Helper to invoke handlers /// Helper to invoke handlers
@ -679,12 +712,24 @@ namespace CryptoExchange.Net.Sockets
var checkTime = DateTime.UtcNow; var checkTime = DateTime.UtcNow;
if (checkTime - _lastReceivedMessagesUpdate > TimeSpan.FromSeconds(1)) if (checkTime - _lastReceivedMessagesUpdate > TimeSpan.FromSeconds(1))
{ {
foreach (var msgTime in _receivedMessages.Keys.ToList()) foreach (var msg in _receivedMessages.ToList()) // To list here because we're removing from the list
if (checkTime - msgTime > TimeSpan.FromSeconds(3)) if (checkTime - msg.Timestamp > TimeSpan.FromSeconds(3))
_receivedMessages.Remove(msgTime); _receivedMessages.Remove(msg);
_lastReceivedMessagesUpdate = checkTime; _lastReceivedMessagesUpdate = checkTime;
} }
} }
} }
internal struct ReceiveItem
{
public DateTime Timestamp { get; set; }
public int Bytes { get; set; }
public ReceiveItem(DateTime timestamp, int bytes)
{
Timestamp = timestamp;
Bytes = bytes;
}
}
} }