1
0
mirror of https://github.com/JKorf/CryptoExchange.Net.git synced 2026-08-20 04:42:57 +00:00

Squashed commit of the following:

commit 1ca93ce870468c7effcc69a05b1675f855598f3e
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Aug 12 13:44:03 2021 +0200

    Version 4.0.0 release

commit f8cefe72cae8b845aa995d16415f160228f5dfc4
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Aug 9 11:46:50 2021 +0200

    Fix for processing a duplicate message in symbol order book

commit f3573e414f80ea622caadb38f9e020f2eab7c834
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Aug 9 11:36:50 2021 +0200

    Updated version

commit 170a3b5c83cd500f0adb5cf74eaaa9c1a8674a10
Merge: 73a0e2c 0d43f6e
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Aug 9 11:33:59 2021 +0200

    Merge branch 'feature/replace-websocket4net' of https://github.com/JKorf/CryptoExchange.Net into feature/replace-websocket4net

commit 73a0e2cb62f8d51b4b8fe1b29fbf16f07ebf13e0
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Aug 9 11:33:45 2021 +0200

    Fixed processing issue in SymbolOrderBook

commit 0d43f6e14e9b61af9bb3250fd72559a5fbf5300a
Author: Jan Korf <jankorf91@gmail.com>
Date:   Sat Jul 31 14:48:23 2021 +0200

    Updated version

commit 037d765fc73740d2aa2159bce6d57f01d989bdc2
Author: Jan Korf <jankorf91@gmail.com>
Date:   Sat Jul 31 11:14:42 2021 +0200

    Socket fixes

commit 13cf3e27b9e91b252368a5dc799363111eed9148
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jul 26 09:55:51 2021 +0200

    Updated version

commit 333c6c4207cafbfd09b37743fb36008f87939666
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jul 26 09:50:35 2021 +0200

    Update CryptoExchangeWebSocketClient.cs

commit ad2b6284b042cfa846e55f8b5f53b2397039dff7
Merge: 64bdcdf 2591cc6
Author: Jan Korf <jankorf91@gmail.com>
Date:   Sun Jul 25 22:44:49 2021 +0200

    Merge branch 'feature/replace-websocket4net' of https://github.com/jkorf/CryptoExchange.Net into feature/replace-websocket4net

commit 64bdcdf087d56b8470baedac1ac86d263ad72490
Author: Jan Korf <jankorf91@gmail.com>
Date:   Sun Jul 25 22:44:03 2021 +0200

    Fix for deadlock

commit 2591cc6782e281595c436ccb4b74a9c7c7f5dc57
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Jul 15 15:10:08 2021 +0200

    Cleanup

commit b3b6235b6edf0ea1a6437239919666d08c274129
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Jul 9 16:14:33 2021 +0200

    Updated version

commit 12975fd13f7884382fea608d774b1e0ac384cb70
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Jul 9 16:12:04 2021 +0200

    Async postfix for order book methods

commit d49d59094e18c83de994a1b591f906f7efe916c5
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Jul 9 15:47:38 2021 +0200

    Renamed async methods with Async post fixes

commit cbe103930ab90378507780cb150596abcb15eb3f
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Jul 8 09:29:34 2021 +0200

    Added Book property on SymbolOrderBook

commit ecc101aed11bab73c49fadc93d3ca4607094d92a
Merge: 181f942 a172461
Author: Jan Korf <jankorf91@gmail.com>
Date:   Wed Jul 7 23:38:58 2021 +0200

    Merge branch 'feature/replace-websocket4net' of https://github.com/jkorf/CryptoExchange.Net into feature/replace-websocket4net

commit 181f942e2137ff5dfede5365012e24dfb2f07cf9
Author: Jan Korf <jankorf91@gmail.com>
Date:   Wed Jul 7 23:38:49 2021 +0200

    Added CalculateAverageFillPrice to order book

commit a17246153df463aa881e9808ffb87fa25f144d90
Author: Jkorf <jankorf91@gmail.com>
Date:   Wed Jul 7 13:11:39 2021 +0200

    Updated version

commit c60f138ae846a991662e7544d45845decd25cc10
Author: Jkorf <jankorf91@gmail.com>
Date:   Wed Jul 7 13:05:44 2021 +0200

    Fix not logging responses with LogLevel.Debug

commit 91f168fd25150b3048346bcc6acc549ee3685e50
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jul 5 10:39:48 2021 +0200

    Added ExchangeHelpers to ReadMe

commit ff6c02e574d3f8a270e2960fdda0222c53457868
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jul 5 10:34:25 2021 +0200

    Added some helper methods, some code comments

commit 55900a3db938f032436303c2399f41b7a3a5fef1
Merge: 9067a8a 7ab6bb0
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jul 5 09:24:43 2021 +0200

    Merge branch 'master' into feature/replace-websocket4net

commit 9067a8a82c5d8c1e1f6ba0f2600539efd7f1a122
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Jul 2 16:03:38 2021 +0200

    Update README.md

commit 0f202d69c7e3db71f66dcfef5673b97f56451a40
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Jun 25 16:37:06 2021 +0200

    Code comments, added console logger

commit 52160c6dc1bbaca3cc498c49ec0dd71310d5102b
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Jun 24 16:47:04 2021 +0200

    Added/cleaned up code comments

commit 95771c5c4ae3a74963fea5a01e05559596b1b39d
Author: Jkorf <jankorf91@gmail.com>
Date:   Tue Jun 22 14:22:15 2021 +0200

    Additional info socket connection error

commit 6a90e2316d54d42c0f5b7772d60d4861ff340c5a
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Jun 17 16:10:43 2021 +0200

    Updated version

commit b138c1050372b5d5fbdc3b2a33d3c09b677a669a
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Jun 17 16:08:19 2021 +0200

    Fix not receiving OriginalData in output

commit 462f44cf45e1bc7ee333e37ad0a778185d84fa58
Author: Jan Korf <jankorf91@gmail.com>
Date:   Wed Jun 16 22:35:03 2021 +0200

    Fix invalidoperation in order book

commit aa7414321b1297487a5133fa0a7e5ede059a6939
Author: Jan Korf <jankorf91@gmail.com>
Date:   Sun Jun 13 20:56:01 2021 +0200

    logging no data task

commit 22aa5928f5cb11ac5877bc4c606d64550aad3f0c
Author: Jan Korf <jankorf91@gmail.com>
Date:   Tue Jun 8 19:13:18 2021 +0200

    Updated version

commit 1ceb22994a5cdf779de8890e39101956728ab80c
Author: Jan Korf <jankorf91@gmail.com>
Date:   Tue Jun 8 19:11:20 2021 +0200

    Fixed exception on .net framework when creating socket

commit 971cab739dd543de0122c9bc12819f57d4df15e3
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jun 7 14:41:27 2021 +0200

    Updated unit test packages

commit 216213d5ad0e14c6cd7b8e22131b8b07338bacfc
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon Jun 7 10:46:57 2021 +0200

    Updated version

commit ce2c7ddc182599c5ca9ef0eb64e14906c8b734e1
Merge: b219705 55aa77e
Author: Jan Korf <jankorf91@gmail.com>
Date:   Mon Jun 7 09:29:57 2021 +0200

    Merge pull request #96 from ridicoulous/master

    iexchange client improvements

commit b21970552602eb853a061034a5c223a381e7465b
Author: Jkorf <jankorf91@gmail.com>
Date:   Tue Jun 1 14:55:02 2021 +0200

    Updated version

commit dd2cf84c163920e545ec09e1b0d29ab295f2fbe2
Author: Jkorf <jankorf91@gmail.com>
Date:   Tue Jun 1 14:52:55 2021 +0200

    Added tests for LogLevel null

commit 975003284f53094750ec3d4a608d814a6d70f745
Author: Jkorf <jankorf91@gmail.com>
Date:   Tue Jun 1 14:42:59 2021 +0200

    Made LogLevel nullable in options, moved log formatting to the ILogger implementation

commit 1c1de5651e31e9288b4fd125b0545efbfa9098f7
Merge: 34bf986 e7838ab
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon May 31 10:16:52 2021 +0200

    Merge branch 'feature/replace-websocket4net' of https://github.com/JKorf/CryptoExchange.Net into feature/replace-websocket4net

commit 34bf9867dcd2c2b195079094560351d0db2dac0f
Author: Jkorf <jankorf91@gmail.com>
Date:   Mon May 31 10:16:49 2021 +0200

    fixed some axync issues

commit e7838ab9e8310b4ae02c172f0a764aad8ca8fd4e
Author: Jan Korf <jankorf91@gmail.com>
Date:   Wed May 26 13:46:40 2021 +0200

    Added Discord link to ReadMe

commit 502939f57cf8deac1809c4bd2c63af4acc62bd43
Author: Jan Korf <jankorf91@gmail.com>
Date:   Wed May 26 11:12:59 2021 +0200

    Updated version

commit 92b745ca291259eb246572c8029709b87ddbf2d3
Author: Jan Korf <jankorf91@gmail.com>
Date:   Tue May 25 21:52:47 2021 +0200

    Refactored logging to use ILogger

commit b4904b5e4a239ffb29f00b13a314fea33d45d9cb
Author: Jan Korf <jankorf91@gmail.com>
Date:   Tue May 25 14:07:01 2021 +0200

    Added optional json output, added DataEvent for socket updates

commit 55aa77e926
Author: Artem Kurianov <artemkuryanov@gmail.com>
Date:   Fri May 14 13:11:05 2021 +0000

    added order time

commit efe70445ed
Author: Artem Kurianov <artemkuryanov@gmail.com>
Date:   Fri May 14 13:08:58 2021 +0000

    iexchange client improvements

commit 8f0943f0f0469b42f40334257f0f3ca5e39e3bd9
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu May 6 10:24:33 2021 +0200

    Updated version

commit 17d1e5f71bd1986eea0e8273da070f3615d3e378
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu May 6 10:01:24 2021 +0200

    Added missing configureawaits

commit ed748aa474e0d52a78bc15b9b0aa0a9b4d8dd35e
Author: Jan Korf <jankorf91@gmail.com>
Date:   Fri Apr 30 23:00:07 2021 +0200

    Updated version

commit 1ae545563497889c75ed6183377e759da5beed61
Author: Jan Korf <jankorf91@gmail.com>
Date:   Fri Apr 30 21:00:40 2021 +0200

    Updated socket closing

commit 8243ad60dc64f96ed262ec54cbd6c55553c056be
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Apr 30 15:48:36 2021 +0200

    Updated version

commit 4299f238f3debc2b1b062eb7cde195a3d64dbdfc
Author: Jan Korf <jankorf91@gmail.com>
Date:   Fri Apr 30 15:44:32 2021 +0200

    Fix for closing socket without timeout task

commit 71f49cfe5142cb70fb651936e74b8eef5b7350d4
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Apr 30 14:59:10 2021 +0200

    Updated version

commit 5d669068ec0a7241daef383c6867c2e22ec21ed3
Author: Jkorf <jankorf91@gmail.com>
Date:   Fri Apr 30 14:56:15 2021 +0200

    Renaming, cleanup

    handler -> subscription
    socket (SocketConnection) -> socketConnection

commit 0fa13e286060cd3b96b808406434092c0e89e89d
Author: Jkorf <jankorf91@gmail.com>
Date:   Thu Apr 29 16:20:41 2021 +0200

    Initial work replacing Websocket4Net with ClientWebSocket
This commit is contained in:
Jkorf
2021-08-12 13:46:39 +02:00
parent 7c10c58779
commit dcb2fa35af
61 changed files with 2696 additions and 1655 deletions
-422
View File
@@ -1,422 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using System.Threading;
using System.Threading.Tasks;
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging;
using SuperSocket.ClientEngine;
using SuperSocket.ClientEngine.Proxy;
using WebSocket4Net;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// Socket implementation
/// </summary>
public class BaseSocket: IWebsocket
{
internal static int lastStreamId;
private static readonly object streamIdLock = new object();
/// <summary>
/// Socket
/// </summary>
protected WebSocket? socket;
/// <summary>
/// Log
/// </summary>
protected Log log;
private readonly object socketLock = new object();
/// <summary>
/// Error handlers
/// </summary>
protected readonly List<Action<Exception>> errorHandlers = new List<Action<Exception>>();
/// <summary>
/// Open handlers
/// </summary>
protected readonly List<Action> openHandlers = new List<Action>();
/// <summary>
/// Close handlers
/// </summary>
protected readonly List<Action> closeHandlers = new List<Action>();
/// <summary>
/// Message handlers
/// </summary>
protected readonly List<Action<string>> messageHandlers = new List<Action<string>>();
private readonly IDictionary<string, string> cookies;
private readonly IDictionary<string, string> headers;
private HttpConnectProxy? proxy;
/// <summary>
/// Id
/// </summary>
public int Id { get; }
/// <summary>
/// If is reconnecting
/// </summary>
public bool Reconnecting { get; set; }
/// <summary>
/// Origin
/// </summary>
public string? Origin { get; set; }
/// <summary>
/// Url
/// </summary>
public string Url { get; }
/// <summary>
/// Is closed
/// </summary>
public bool IsClosed => socket?.State == null || socket.State == WebSocketState.Closed;
/// <summary>
/// Is open
/// </summary>
public bool IsOpen => socket?.State == WebSocketState.Open;
/// <summary>
/// Protocols
/// </summary>
public SslProtocols SSLProtocols { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
/// <summary>
/// Interpreter for bytes
/// </summary>
public Func<byte[], string>? DataInterpreterBytes { get; set; }
/// <summary>
/// Interpreter for strings
/// </summary>
public Func<string, string>? DataInterpreterString { get; set; }
/// <summary>
/// Last action time
/// </summary>
public DateTime LastActionTime { get; private set; }
/// <summary>
/// Timeout
/// </summary>
public TimeSpan Timeout { get; set; }
private Task? timeoutTask;
/// <summary>
/// Socket state
/// </summary>
public WebSocketState SocketState => socket?.State ?? WebSocketState.None;
/// <summary>
/// ctor
/// </summary>
/// <param name="log"></param>
/// <param name="url"></param>
public BaseSocket(Log log, string url):this(log, url, new Dictionary<string, string>(), new Dictionary<string, string>())
{
}
/// <summary>
/// ctor
/// </summary>
/// <param name="log"></param>
/// <param name="url"></param>
/// <param name="cookies"></param>
/// <param name="headers"></param>
public BaseSocket(Log log, string url, IDictionary<string, string> cookies, IDictionary<string, string> headers)
{
Id = NextStreamId();
this.log = log;
Url = url;
this.cookies = cookies;
this.headers = headers;
}
private void HandleByteData(byte[] data)
{
if (DataInterpreterBytes == null)
throw new Exception("Byte interpreter not set while receiving byte data");
try
{
var message = DataInterpreterBytes(data);
Handle(messageHandlers, message);
}
catch (Exception ex)
{
log.Write(LogVerbosity.Error, $"{Id} Something went wrong while processing a byte message from the socket: {ex}");
}
}
private void HandleStringData(string data)
{
try
{
if (DataInterpreterString != null)
data = DataInterpreterString(data);
Handle(messageHandlers, data);
}
catch (Exception ex)
{
log.Write(LogVerbosity.Error, $"{Id} Something went wrong while processing a string message from the socket: {ex}");
}
}
/// <summary>
/// On close
/// </summary>
public event Action OnClose
{
add => closeHandlers.Add(value);
remove => closeHandlers.Remove(value);
}
/// <summary>
/// On message
/// </summary>
public event Action<string> OnMessage
{
add => messageHandlers.Add(value);
remove => messageHandlers.Remove(value);
}
/// <summary>
/// On error
/// </summary>
public event Action<Exception> OnError
{
add => errorHandlers.Add(value);
remove => errorHandlers.Remove(value);
}
/// <summary>
/// On open
/// </summary>
public event Action OnOpen
{
add => openHandlers.Add(value);
remove => openHandlers.Remove(value);
}
/// <summary>
/// Handle
/// </summary>
/// <param name="handlers"></param>
protected void Handle(List<Action> handlers)
{
LastActionTime = DateTime.UtcNow;
foreach (var handle in new List<Action>(handlers))
handle?.Invoke();
}
/// <summary>
/// Handle
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="handlers"></param>
/// <param name="data"></param>
protected void Handle<T>(List<Action<T>> handlers, T data)
{
LastActionTime = DateTime.UtcNow;
foreach (var handle in new List<Action<T>>(handlers))
handle?.Invoke(data);
}
/// <summary>
/// Checks if timed out
/// </summary>
/// <returns></returns>
protected async Task CheckTimeout()
{
while (true)
{
lock (socketLock)
{
if (socket == null || socket.State != WebSocketState.Open)
return;
if (DateTime.UtcNow - LastActionTime > Timeout)
{
log.Write(LogVerbosity.Warning, $"No data received for {Timeout}, reconnecting socket");
_ = Close().ConfigureAwait(false);
return;
}
}
await Task.Delay(500).ConfigureAwait(false);
}
}
/// <summary>
/// Close socket
/// </summary>
/// <returns></returns>
public virtual async Task Close()
{
await Task.Run(() =>
{
lock (socketLock)
{
if (socket == null || IsClosed)
{
log?.Write(LogVerbosity.Debug, $"Socket {Id} was already closed/disposed");
return;
}
var waitLock = new object();
log?.Write(LogVerbosity.Debug, $"Socket {Id} closing");
ManualResetEvent? evnt = new ManualResetEvent(false);
var handler = new EventHandler((o, a) =>
{
lock(waitLock)
evnt?.Set();
});
socket.Closed += handler;
socket.Close();
evnt.WaitOne(2000);
lock (waitLock)
{
socket.Closed -= handler;
evnt.Dispose();
evnt = null;
}
log?.Write(LogVerbosity.Debug, $"Socket {Id} closed");
}
}).ConfigureAwait(false);
}
/// <summary>
/// Reset socket
/// </summary>
public virtual void Reset()
{
lock (socketLock)
{
log.Write(LogVerbosity.Debug, $"Socket {Id} resetting");
socket?.Dispose();
socket = null;
}
}
/// <summary>
/// Send data
/// </summary>
/// <param name="data"></param>
public virtual void Send(string data)
{
socket?.Send(data);
}
/// <summary>
/// Connect socket
/// </summary>
/// <returns></returns>
public virtual Task<bool> Connect()
{
if (socket == null)
{
socket = new WebSocket(Url, cookies: cookies.ToList(), customHeaderItems: headers.ToList(), origin: Origin ?? "")
{
EnableAutoSendPing = true,
AutoSendPingInterval = 10
};
if (proxy != null)
socket.Proxy = proxy;
socket.Security.EnabledSslProtocols = SSLProtocols;
socket.Opened += (o, s) => Handle(openHandlers);
socket.Closed += (o, s) => Handle(closeHandlers);
socket.Error += (o, s) => Handle(errorHandlers, s.Exception);
socket.MessageReceived += (o, s) => HandleStringData(s.Message);
socket.DataReceived += (o, s) => HandleByteData(s.Data);
}
return Task.Run(() =>
{
bool connected;
lock (socketLock)
{
log?.Write(LogVerbosity.Debug, $"Socket {Id} connecting");
var waitLock = new object();
ManualResetEvent? evnt = new ManualResetEvent(false);
var handler = new EventHandler((o, a) =>
{
lock (waitLock)
evnt?.Set();
});
var errorHandler = new EventHandler<ErrorEventArgs>((o, a) =>
{
lock(waitLock)
evnt?.Set();
});
socket.Opened += handler;
socket.Closed += handler;
socket.Error += errorHandler;
socket.Open();
evnt.WaitOne(TimeSpan.FromSeconds(15));
lock (waitLock)
{
socket.Opened -= handler;
socket.Closed -= handler;
socket.Error -= errorHandler;
evnt.Dispose();
evnt = null;
}
connected = socket.State == WebSocketState.Open;
if (connected)
{
log?.Write(LogVerbosity.Debug, $"Socket {Id} connected");
if ((timeoutTask == null || timeoutTask.IsCompleted) && Timeout != default)
timeoutTask = Task.Run(CheckTimeout);
}
else
{
log?.Write(LogVerbosity.Debug, $"Socket {Id} connection failed, state: " + socket.State);
}
}
if (socket.State == WebSocketState.Connecting)
socket.Close();
return connected;
});
}
/// <summary>
/// Set a proxy
/// </summary>
/// <param name="host"></param>
/// <param name="port"></param>
public virtual void SetProxy(string host, int port)
{
proxy = IPAddress.TryParse(host, out var address)
? new HttpConnectProxy(new IPEndPoint(address, port))
: new HttpConnectProxy(new DnsEndPoint(host, port));
}
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
lock (socketLock)
{
if (socket != null)
log?.Write(LogVerbosity.Debug, $"Socket {Id} disposing websocket");
socket?.Dispose();
socket = null;
errorHandlers.Clear();
openHandlers.Clear();
closeHandlers.Clear();
messageHandlers.Clear();
}
}
private static int NextStreamId()
{
lock (streamIdLock)
{
lastStreamId++;
return lastStreamId;
}
}
}
}
@@ -0,0 +1,561 @@
using CryptoExchange.Net.Interfaces;
using CryptoExchange.Net.Logging;
using CryptoExchange.Net.Objects;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.WebSockets;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// A wrapper around the ClientWebSocket
/// </summary>
public class CryptoExchangeWebSocketClient : IWebsocket
{
internal static int lastStreamId;
private static readonly object streamIdLock = new object();
private ClientWebSocket _socket;
private Task? _sendTask;
private Task? _receiveTask;
private Task? _timeoutTask;
private readonly AutoResetEvent _sendEvent;
private readonly ConcurrentQueue<byte[]> _sendBuffer;
private readonly IDictionary<string, string> cookies;
private readonly IDictionary<string, string> headers;
private CancellationTokenSource _ctsSource;
private bool _closing;
/// <summary>
/// Log
/// </summary>
protected Log log;
/// <summary>
/// Handlers for when an error happens on the socket
/// </summary>
protected readonly List<Action<Exception>> errorHandlers = new List<Action<Exception>>();
/// <summary>
/// Handlers for when the socket connection is opened
/// </summary>
protected readonly List<Action> openHandlers = new List<Action>();
/// <summary>
/// Handlers for when the connection is closed
/// </summary>
protected readonly List<Action> closeHandlers = new List<Action>();
/// <summary>
/// Handlers for when a message is received
/// </summary>
protected readonly List<Action<string>> messageHandlers = new List<Action<string>>();
/// <summary>
/// The id of this socket
/// </summary>
public int Id { get; }
/// <inheritdoc />
public string? Origin { get; set; }
/// <summary>
/// Whether this socket is currently reconnecting
/// </summary>
public bool Reconnecting { get; set; }
/// <summary>
/// The timestamp this socket has been active for the last time
/// </summary>
public DateTime LastActionTime { get; private set; }
/// <summary>
/// Delegate used for processing byte data received from socket connections before it is processed by handlers
/// </summary>
public Func<byte[], string>? DataInterpreterBytes { get; set; }
/// <summary>
/// Delegate used for processing string data received from socket connections before it is processed by handlers
/// </summary>
public Func<string, string>? DataInterpreterString { get; set; }
/// <summary>
/// Url this socket connects to
/// </summary>
public string Url { get; }
/// <summary>
/// If the connection is closed
/// </summary>
public bool IsClosed => _socket.State == WebSocketState.Closed;
/// <summary>
/// If the connection is open
/// </summary>
public bool IsOpen => _socket.State == WebSocketState.Open;
/// <summary>
/// Ssl protocols supported. NOT USED BY THIS IMPLEMENTATION
/// </summary>
public SslProtocols SSLProtocols { get; set; }
private Encoding _encoding = Encoding.UTF8;
/// <summary>
/// Encoding used for decoding the received bytes into a string
/// </summary>
public Encoding? Encoding
{
get => _encoding;
set
{
if(value != null)
_encoding = value;
}
}
/// <summary>
/// The timespan no data is received on the socket. If no data is received within this time an error is generated
/// </summary>
public TimeSpan Timeout { get; set; }
/// <summary>
/// Socket closed event
/// </summary>
public event Action OnClose
{
add => closeHandlers.Add(value);
remove => closeHandlers.Remove(value);
}
/// <summary>
/// Socket message received event
/// </summary>
public event Action<string> OnMessage
{
add => messageHandlers.Add(value);
remove => messageHandlers.Remove(value);
}
/// <summary>
/// Socket error event
/// </summary>
public event Action<Exception> OnError
{
add => errorHandlers.Add(value);
remove => errorHandlers.Remove(value);
}
/// <summary>
/// Socket opened event
/// </summary>
public event Action OnOpen
{
add => openHandlers.Add(value);
remove => openHandlers.Remove(value);
}
/// <summary>
/// ctor
/// </summary>
/// <param name="log">The log object to use</param>
/// <param name="url">The url the socket should connect to</param>
public CryptoExchangeWebSocketClient(Log log, string url) : this(log, url, new Dictionary<string, string>(), new Dictionary<string, string>())
{
}
/// <summary>
/// ctor
/// </summary>
/// <param name="log">The log object to use</param>
/// <param name="url">The url the socket should connect to</param>
/// <param name="cookies">Cookies to sent in the socket connection request</param>
/// <param name="headers">Headers to sent in the socket connection request</param>
public CryptoExchangeWebSocketClient(Log log, string url, IDictionary<string, string> cookies, IDictionary<string, string> headers)
{
Id = NextStreamId();
this.log = log;
Url = url;
this.cookies = cookies;
this.headers = headers;
_sendEvent = new AutoResetEvent(false);
_sendBuffer = new ConcurrentQueue<byte[]>();
_ctsSource = new CancellationTokenSource();
_socket = CreateSocket();
}
/// <summary>
/// Set a proxy to use. Should be set before connecting
/// </summary>
/// <param name="proxy"></param>
public virtual void SetProxy(ApiProxy proxy)
{
_socket.Options.Proxy = new WebProxy(proxy.Host, proxy.Port);
if (proxy.Login != null)
_socket.Options.Proxy.Credentials = new NetworkCredential(proxy.Login, proxy.Password);
}
/// <summary>
/// Connect the websocket
/// </summary>
/// <returns>True if successfull</returns>
public virtual async Task<bool> ConnectAsync()
{
log.Write(LogLevel.Debug, $"Socket {Id} connecting");
try
{
using CancellationTokenSource tcs = new CancellationTokenSource(TimeSpan.FromSeconds(10));
await _socket.ConnectAsync(new Uri(Url), default).ConfigureAwait(false);
Handle(openHandlers);
}
catch (Exception e)
{
log.Write(LogLevel.Debug, $"Socket {Id} connection failed: " + e.ToLogString());
return false;
}
log.Write(LogLevel.Debug, $"Socket {Id} connected");
_sendTask = Task.Run(async () => await SendLoopAsync().ConfigureAwait(false));
_receiveTask = Task.Run(ReceiveLoopAsync);
if (Timeout != default)
_timeoutTask = Task.Run(CheckTimeoutAsync);
return true;
}
/// <summary>
/// Send data over the websocket
/// </summary>
/// <param name="data">Data to send</param>
public virtual void Send(string data)
{
if (_closing)
throw new InvalidOperationException("Can't send data when socket is not connected");
var bytes = _encoding.GetBytes(data);
_sendBuffer.Enqueue(bytes);
_sendEvent.Set();
}
/// <summary>
/// Close the websocket
/// </summary>
/// <returns></returns>
public virtual async Task CloseAsync()
{
log.Write(LogLevel.Debug, $"Socket {Id} closing");
await CloseInternalAsync(true, true).ConfigureAwait(false);
}
/// <summary>
/// Internal close method, will wait for each task to complete to gracefully close
/// </summary>
/// <param name="waitSend"></param>
/// <param name="waitReceive"></param>
/// <returns></returns>
private async Task CloseInternalAsync(bool waitSend, bool waitReceive)
{
if (_closing)
return;
_closing = true;
var tasksToAwait = new List<Task>();
if (_socket.State == WebSocketState.Open)
tasksToAwait.Add(_socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Closing", default));
_ctsSource.Cancel();
_sendEvent.Set();
if (waitSend)
tasksToAwait.Add(_sendTask!);
if (waitReceive)
tasksToAwait.Add(_receiveTask!);
if (_timeoutTask != null)
tasksToAwait.Add(_timeoutTask);
await Task.WhenAll(tasksToAwait).ConfigureAwait(false);
log.Write(LogLevel.Debug, $"Socket {Id} closed");
Handle(closeHandlers);
}
/// <summary>
/// Dispose the socket
/// </summary>
public void Dispose()
{
log.Write(LogLevel.Debug, $"Socket {Id} disposing");
_socket.Dispose();
_ctsSource.Dispose();
errorHandlers.Clear();
openHandlers.Clear();
closeHandlers.Clear();
messageHandlers.Clear();
}
/// <summary>
/// Reset the socket so a new connection can be attempted after it has been connected before
/// </summary>
public void Reset()
{
log.Write(LogLevel.Debug, $"Socket {Id} resetting");
_ctsSource = new CancellationTokenSource();
_closing = false;
_socket = CreateSocket();
}
/// <summary>
/// Create the socket object
/// </summary>
private ClientWebSocket CreateSocket()
{
var cookieContainer = new CookieContainer();
foreach (var cookie in cookies)
cookieContainer.Add(new Cookie(cookie.Key, cookie.Value));
var socket = new ClientWebSocket();
socket.Options.Cookies = cookieContainer;
foreach (var header in headers)
socket.Options.SetRequestHeader(header.Key, header.Value);
socket.Options.KeepAliveInterval = TimeSpan.FromSeconds(10);
socket.Options.SetBuffer(65536, 65536); // Setting it to anything bigger than 65536 throws an exception in .net framework
return socket;
}
/// <summary>
/// Loop for sending data
/// </summary>
/// <returns></returns>
private async Task SendLoopAsync()
{
while (true)
{
_sendEvent.WaitOne();
if (_closing)
break;
if (!_sendBuffer.TryDequeue(out var data))
continue;
try
{
await _socket.SendAsync(new ArraySegment<byte>(data, 0, data.Length), WebSocketMessageType.Text, true, _ctsSource.Token).ConfigureAwait(false);
}
catch (TaskCanceledException)
{
// cancelled
break;
}
catch (WebSocketException wse)
{
// Connection closed unexpectedly
Handle(errorHandlers, wse);
await CloseInternalAsync(false, true).ConfigureAwait(false);
break;
}
}
}
/// <summary>
/// Loop for receiving and reassembling data
/// </summary>
/// <returns></returns>
private async Task ReceiveLoopAsync()
{
var buffer = new ArraySegment<byte>(new byte[4096]);
var received = 0;
while (true)
{
if (_closing)
break;
MemoryStream? memoryStream = null;
WebSocketReceiveResult? receiveResult = null;
bool multiPartMessage = false;
while (true)
{
try
{
receiveResult = await _socket.ReceiveAsync(buffer, _ctsSource.Token).ConfigureAwait(false);
received += receiveResult.Count;
}
catch (TaskCanceledException)
{
// Cancelled
break;
}
catch (WebSocketException wse)
{
// Connection closed unexpectedly
Handle(errorHandlers, wse);
await CloseInternalAsync(true, false).ConfigureAwait(false);
break;
}
if (receiveResult.MessageType == WebSocketMessageType.Close)
{
// Connection closed unexpectedly
log.Write(LogLevel.Debug, $"Socket {Id} received `Close` message");
await CloseInternalAsync(true, false).ConfigureAwait(false);
break;
}
if (!receiveResult.EndOfMessage)
{
// We received data, but it is not complete, write it to a memory stream for reassembling
multiPartMessage = true;
if (memoryStream == null)
memoryStream = new MemoryStream();
await memoryStream.WriteAsync(buffer.Array, buffer.Offset, receiveResult.Count).ConfigureAwait(false);
}
else
{
if (!multiPartMessage)
// Received a complete message and it's not multi part
HandleMessage(buffer.Array, buffer.Offset, receiveResult.Count, receiveResult.MessageType);
else
// Received the end of a multipart message, write to memory stream for reassembling
await memoryStream!.WriteAsync(buffer.Array, buffer.Offset, receiveResult.Count).ConfigureAwait(false);
break;
}
}
if (receiveResult?.MessageType == WebSocketMessageType.Close)
{
// Received close message
break;
}
if (receiveResult == null || _closing)
{
// Error during receiving or cancellation requested, stop.
break;
}
if (multiPartMessage)
{
// Reassemble complete message from memory stream
HandleMessage(memoryStream!.ToArray(), 0, (int)memoryStream.Length, receiveResult.MessageType);
memoryStream.Dispose();
}
}
}
/// <summary>
/// Handles the message
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <param name="count"></param>
/// <param name="messageType"></param>
private void HandleMessage(byte[] data, int offset, int count, WebSocketMessageType messageType)
{
string strData;
if (messageType == WebSocketMessageType.Binary)
{
if (DataInterpreterBytes == null)
throw new Exception("Byte interpreter not set while receiving byte data");
try
{
strData = DataInterpreterBytes(data);
}
catch(Exception e)
{
log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during byte data interpretation: " + e.ToLogString());
return;
}
}
else
strData = _encoding.GetString(data, offset, count);
if (DataInterpreterString != null)
{
try
{
strData = DataInterpreterString(strData);
}
catch(Exception e)
{
log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during string data interpretation: " + e.ToLogString());
return;
}
}
try
{
Handle(messageHandlers, strData);
}
catch(Exception e)
{
log.Write(LogLevel.Error, $"Socket {Id} unhandled exception during message processing: " + e.ToLogString());
return;
}
}
/// <summary>
/// Checks if there is no data received for a period longer than the specified timeout
/// </summary>
/// <returns></returns>
protected async Task CheckTimeoutAsync()
{
log.Write(LogLevel.Debug, $"Socket {Id} Starting task checking for no data received for {Timeout}");
while (true)
{
if (_closing)
return;
if (DateTime.UtcNow - LastActionTime > Timeout)
{
log.Write(LogLevel.Warning, $"Socket {Id} No data received for {Timeout}, reconnecting socket");
_ = CloseAsync().ConfigureAwait(false);
return;
}
try
{
await Task.Delay(500, _ctsSource.Token).ConfigureAwait(false);
}
catch(TaskCanceledException)
{
// cancelled
return;
}
}
}
/// <summary>
/// Helper to invoke handlers
/// </summary>
/// <param name="handlers"></param>
protected void Handle(List<Action> handlers)
{
LastActionTime = DateTime.UtcNow;
foreach (var handle in new List<Action>(handlers))
handle?.Invoke();
}
/// <summary>
/// Helper to invoke handlers
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="handlers"></param>
/// <param name="data"></param>
protected void Handle<T>(List<Action<T>> handlers, T data)
{
LastActionTime = DateTime.UtcNow;
foreach (var handle in new List<Action<T>>(handlers))
handle?.Invoke(data);
}
/// <summary>
/// Get the next identifier
/// </summary>
/// <returns></returns>
private static int NextStreamId()
{
lock (streamIdLock)
{
lastStreamId++;
return lastStreamId;
}
}
}
}
+72
View File
@@ -0,0 +1,72 @@
using System;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// An update received from a socket update subscription
/// </summary>
/// <typeparam name="T">The type of the data</typeparam>
public class DataEvent<T>
{
/// <summary>
/// The timestamp the data was received
/// </summary>
public DateTime Timestamp { get; set; }
/// <summary>
/// The topic of the update, what symbol/asset etc..
/// </summary>
public string? Topic { get; set; }
/// <summary>
/// The original data that was received, only available when OutputOriginalData is set to true in the client options
/// </summary>
public string? OriginalData { get; set; }
/// <summary>
/// The received data deserialized into an object
/// </summary>
public T Data { get; set; }
internal DataEvent(T data, DateTime timestamp)
{
Data = data;
Timestamp = timestamp;
}
internal DataEvent(T data, string? topic, DateTime timestamp)
{
Data = data;
Topic = topic;
Timestamp = timestamp;
}
internal DataEvent(T data, string? topic, string? originalData, DateTime timestamp)
{
Data = data;
Topic = topic;
OriginalData = originalData;
Timestamp = timestamp;
}
/// <summary>
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. Topic, OriginalData and Timestamp will be copied over
/// </summary>
/// <typeparam name="K">The type of the new data</typeparam>
/// <param name="data">The new data</param>
/// <returns></returns>
public DataEvent<K> As<K>(K data)
{
return new DataEvent<K>(data, Topic, OriginalData, Timestamp);
}
/// <summary>
/// Create a new DataEvent with data in the from of type K based on the current DataEvent. OriginalData and Timestamp will be copied over
/// </summary>
/// <typeparam name="K">The type of the new data</typeparam>
/// <param name="data">The new data</param>
/// <param name="topic">The new topic</param>
/// <returns></returns>
public DataEvent<K> As<K>(K data, string? topic)
{
return new DataEvent<K>(data, topic, OriginalData, Timestamp);
}
}
}
@@ -0,0 +1,43 @@
using Newtonsoft.Json.Linq;
using System;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// Message received event
/// </summary>
public class MessageEvent
{
/// <summary>
/// The connection the message was received on
/// </summary>
public SocketConnection Connection { get; set; }
/// <summary>
/// The json object of the data
/// </summary>
public JToken JsonData { get; set; }
/// <summary>
/// The originally received string data
/// </summary>
public string? OriginalData { get; set; }
/// <summary>
/// The timestamp of when the data was received
/// </summary>
public DateTime ReceivedTimestamp { get; set; }
/// <summary>
///
/// </summary>
/// <param name="connection"></param>
/// <param name="jsonData"></param>
/// <param name="originalData"></param>
/// <param name="timestamp"></param>
public MessageEvent(SocketConnection connection, JToken jsonData, string? originalData, DateTime timestamp)
{
Connection = connection;
JsonData = jsonData;
OriginalData = originalData;
ReceivedTimestamp = timestamp;
}
}
}
+88 -69
View File
@@ -8,6 +8,7 @@ using System.Threading.Tasks;
using CryptoExchange.Net.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
namespace CryptoExchange.Net.Sockets
{
@@ -42,12 +43,12 @@ namespace CryptoExchange.Net.Sockets
public event Action<JToken>? UnhandledMessage;
/// <summary>
/// The amount of handlers
/// The amount of subscriptions on this connection
/// </summary>
public int HandlerCount
public int SubscriptionCount
{
get { lock (handlersLock)
return handlers.Count(h => h.UserSubscription); }
get { lock (subscriptionLock)
return subscriptions.Count(h => h.UserSubscription); }
}
/// <summary>
@@ -60,11 +61,11 @@ namespace CryptoExchange.Net.Sockets
public bool Connected { get; private set; }
/// <summary>
/// The socket
/// The underlying socket
/// </summary>
public IWebsocket Socket { get; set; }
/// <summary>
/// If should reconnect upon closing
/// If the socket should be reconnected upon closing
/// </summary>
public bool ShouldReconnect { get; set; }
@@ -84,7 +85,7 @@ namespace CryptoExchange.Net.Sockets
if (pausedActivity != value)
{
pausedActivity = value;
log.Write(LogVerbosity.Debug, "Paused activity: " + value);
log.Write(LogLevel.Debug, "Paused activity: " + value);
if(pausedActivity) ActivityPaused?.Invoke();
else ActivityUnpaused?.Invoke();
}
@@ -92,8 +93,8 @@ namespace CryptoExchange.Net.Sockets
}
private bool pausedActivity;
private readonly List<SocketSubscription> handlers;
private readonly object handlersLock = new object();
private readonly List<SocketSubscription> subscriptions;
private readonly object subscriptionLock = new object();
private bool lostTriggered;
private readonly Log log;
@@ -113,7 +114,7 @@ namespace CryptoExchange.Net.Sockets
pendingRequests = new List<PendingRequest>();
handlers = new List<SocketSubscription>();
subscriptions = new List<SocketSubscription>();
Socket = socket;
Socket.Timeout = client.SocketNoDataTimeout;
@@ -137,9 +138,14 @@ namespace CryptoExchange.Net.Sockets
};
}
/// <summary>
/// Process a message received by the socket
/// </summary>
/// <param name="data"></param>
private void ProcessMessage(string data)
{
log.Write(LogVerbosity.Debug, $"Socket {Socket.Id} received data: " + data);
var timestamp = DateTime.UtcNow;
log.Write(LogLevel.Trace, $"Socket {Socket.Id} received data: " + data);
if (string.IsNullOrEmpty(data)) return;
var tokenData = data.ToJToken(log);
@@ -151,12 +157,14 @@ namespace CryptoExchange.Net.Sockets
return;
}
var messageEvent = new MessageEvent(this, tokenData, socketClient.OutputOriginalData ? data: null, timestamp);
var handledResponse = false;
PendingRequest[] requests;
lock(pendingRequests)
{
requests = pendingRequests.ToArray();
}
// Check if this message is an answer on any pending requests
foreach (var pendingRequest in requests)
{
if (pendingRequest.Check(tokenData))
@@ -176,51 +184,54 @@ namespace CryptoExchange.Net.Sockets
}
}
if (!HandleData(tokenData) && !handledResponse)
// Message was not a request response, check data handlers
if (!HandleData(messageEvent) && !handledResponse)
{
if (!socketClient.UnhandledMessageExpected)
log.Write(LogVerbosity.Warning, "Message not handled: " + tokenData);
log.Write(LogLevel.Warning, $"Socket {Socket.Id} Message not handled: " + tokenData);
UnhandledMessage?.Invoke(tokenData);
}
}
/// <summary>
/// Add handler
/// Add subscription to this connection
/// </summary>
/// <param name="handler"></param>
public void AddHandler(SocketSubscription handler)
/// <param name="subscription"></param>
public void AddSubscription(SocketSubscription subscription)
{
lock(handlersLock)
handlers.Add(handler);
lock(subscriptionLock)
subscriptions.Add(subscription);
}
private bool HandleData(JToken tokenData)
private bool HandleData(MessageEvent messageEvent)
{
SocketSubscription? currentSubscription = null;
try
{
var handled = false;
var sw = Stopwatch.StartNew();
lock (handlersLock)
// Loop the subscriptions to check if any of them signal us that the message is for them
lock (subscriptionLock)
{
foreach (var handler in handlers.ToList())
foreach (var subscription in subscriptions.ToList())
{
currentSubscription = handler;
if (handler.Request == null)
currentSubscription = subscription;
if (subscription.Request == null)
{
if (socketClient.MessageMatchesHandler(tokenData, handler.Identifier!))
if (socketClient.MessageMatchesHandler(messageEvent.JsonData, subscription.Identifier!))
{
handled = true;
handler.MessageHandler(this, tokenData);
subscription.MessageHandler(messageEvent);
}
}
else
{
if (socketClient.MessageMatchesHandler(tokenData, handler.Request))
if (socketClient.MessageMatchesHandler(messageEvent.JsonData, subscription.Request))
{
handled = true;
tokenData = socketClient.ProcessTokenData(tokenData);
handler.MessageHandler(this, tokenData);
messageEvent.JsonData = socketClient.ProcessTokenData(messageEvent.JsonData);
subscription.MessageHandler(messageEvent);
}
}
}
@@ -228,29 +239,29 @@ namespace CryptoExchange.Net.Sockets
sw.Stop();
if (sw.ElapsedMilliseconds > 500)
log.Write(LogVerbosity.Warning, $"Socket {Socket.Id} message processing slow ({sw.ElapsedMilliseconds}ms), consider offloading data handling to another thread. " +
log.Write(LogLevel.Warning, $"Socket {Socket.Id} message processing slow ({sw.ElapsedMilliseconds}ms), consider offloading data handling to another thread. " +
"Data from this socket may arrive late or not at all if message processing is continuously slow.");
else
log.Write(LogVerbosity.Debug, $"Socket {Socket.Id} message processed in {sw.ElapsedMilliseconds}ms");
log.Write(LogLevel.Trace, $"Socket {Socket.Id} message processed in {sw.ElapsedMilliseconds}ms");
return handled;
}
catch (Exception ex)
{
log.Write(LogVerbosity.Error, $"Socket {Socket.Id} Exception during message processing\r\nException: {ex}\r\nData: {tokenData}");
log.Write(LogLevel.Error, $"Socket {Socket.Id} Exception during message processing\r\nException: {ex.ToLogString()}\r\nData: {messageEvent.JsonData}");
currentSubscription?.InvokeExceptionHandler(ex);
return false;
}
}
/// <summary>
/// Send data
/// Send data and wait for an answer
/// </summary>
/// <typeparam name="T">The data type</typeparam>
/// <typeparam name="T">The data type expected in response</typeparam>
/// <param name="obj">The object to send</param>
/// <param name="timeout">The timeout for response</param>
/// <param name="handler">The response handler</param>
/// <returns></returns>
public virtual Task SendAndWait<T>(T obj, TimeSpan timeout, Func<JToken, bool> handler)
public virtual Task SendAndWaitAsync<T>(T obj, TimeSpan timeout, Func<JToken, bool> handler)
{
var pending = new PendingRequest(handler, timeout);
lock (pendingRequests)
@@ -262,7 +273,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Send data to the websocket
/// Send data over the websocket connection
/// </summary>
/// <typeparam name="T">The type of the object to send</typeparam>
/// <param name="obj">The object to send</param>
@@ -276,12 +287,12 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Send string data to the websocket
/// Send string data over the websocket connection
/// </summary>
/// <param name="data">The data to send</param>
public virtual void Send(string data)
{
log.Write(LogVerbosity.Debug, $"Socket {Socket.Id} sending data: {data}");
log.Write(LogLevel.Debug, $"Socket {Socket.Id} sending data: {data}");
Socket.Send(data);
}
@@ -297,11 +308,12 @@ namespace CryptoExchange.Net.Sockets
Socket.Reconnecting = true;
log.Write(LogVerbosity.Info, $"Socket {Socket.Id} Connection lost, will try to reconnect after {socketClient.ReconnectInterval}");
log.Write(LogLevel.Information, $"Socket {Socket.Id} Connection lost, will try to reconnect after {socketClient.ReconnectInterval}");
Task.Run(async () =>
{
while (ShouldReconnect)
{
// Wait a bit before attempting reconnect
await Task.Delay(socketClient.ReconnectInterval).ConfigureAwait(false);
if (!ShouldReconnect)
{
@@ -311,20 +323,21 @@ namespace CryptoExchange.Net.Sockets
}
Socket.Reset();
if (!await Socket.Connect().ConfigureAwait(false))
if (!await Socket.ConnectAsync().ConfigureAwait(false))
{
log.Write(LogVerbosity.Debug, $"Socket {Socket.Id} failed to reconnect");
log.Write(LogLevel.Debug, $"Socket {Socket.Id} failed to reconnect");
continue;
}
// Successfully reconnected
var time = DisconnectTime;
DisconnectTime = null;
log.Write(LogVerbosity.Info, $"Socket {Socket.Id} reconnected after {DateTime.UtcNow - time}");
log.Write(LogLevel.Information, $"Socket {Socket.Id} reconnected after {DateTime.UtcNow - time}");
var reconnectResult = await ProcessReconnect().ConfigureAwait(false);
var reconnectResult = await ProcessReconnectAsync().ConfigureAwait(false);
if (!reconnectResult)
await Socket.Close().ConfigureAwait(false);
await Socket.CloseAsync().ConfigureAwait(false);
else
{
if (lostTriggered)
@@ -342,11 +355,11 @@ namespace CryptoExchange.Net.Sockets
}
else
{
log.Write(LogVerbosity.Info, $"Socket {Socket.Id} closed");
// No reconnecting needed
log.Write(LogLevel.Information, $"Socket {Socket.Id} closed");
if (socketClient.sockets.ContainsKey(Socket.Id))
socketClient.sockets.TryRemove(Socket.Id, out _);
Socket.Dispose();
Closed?.Invoke();
}
}
@@ -356,29 +369,32 @@ namespace CryptoExchange.Net.Sockets
await Task.Run(() => ConnectionRestored?.Invoke(disconnectTime.HasValue ? DateTime.UtcNow - disconnectTime.Value : TimeSpan.FromSeconds(0))).ConfigureAwait(false);
}
private async Task<bool> ProcessReconnect()
private async Task<bool> ProcessReconnectAsync()
{
if (Authenticated)
{
var authResult = await socketClient.AuthenticateSocket(this).ConfigureAwait(false);
// If we reconnected a authenticated connection we need to re-authenticate
var authResult = await socketClient.AuthenticateSocketAsync(this).ConfigureAwait(false);
if (!authResult)
{
log.Write(LogVerbosity.Info, "Authentication failed on reconnected socket. Disconnecting and reconnecting.");
log.Write(LogLevel.Information, $"Socket {Socket.Id} authentication failed on reconnected socket. Disconnecting and reconnecting.");
return false;
}
log.Write(LogVerbosity.Debug, "Authentication succeeded on reconnected socket.");
log.Write(LogLevel.Debug, $"Socket {Socket.Id} authentication succeeded on reconnected socket.");
}
List<SocketSubscription> handlerList;
lock (handlersLock)
handlerList = handlers.Where(h => h.Request != null).ToList();
// Get a list of all subscriptions on the socket
List<SocketSubscription> subscriptionList;
lock (subscriptionLock)
subscriptionList = subscriptions.Where(h => h.Request != null).ToList();
var success = true;
var taskList = new List<Task>();
foreach (var handler in handlerList)
// Foreach subscription which is subscribed by a subscription request we will need to resend that request to resubscribe
foreach (var subscription in subscriptionList)
{
var task = socketClient.SubscribeAndWait(this, handler.Request!, handler).ContinueWith(t =>
var task = socketClient.SubscribeAndWaitAsync(this, subscription.Request!, subscription).ContinueWith(t =>
{
if (!t.Result)
success = false;
@@ -386,14 +402,14 @@ namespace CryptoExchange.Net.Sockets
taskList.Add(task);
}
Task.WaitAll(taskList.ToArray());
await Task.WhenAll(taskList).ConfigureAwait(false);
if (!success)
{
log.Write(LogVerbosity.Debug, "Resubscribing all subscriptions failed on reconnected socket. Disconnecting and reconnecting.");
log.Write(LogLevel.Debug, $"Socket {Socket.Id} resubscribing all subscriptions failed on reconnected socket. Disconnecting and reconnecting.");
return false;
}
log.Write(LogVerbosity.Debug, "All subscription successfully resubscribed on reconnected socket.");
log.Write(LogLevel.Debug, $"Socket {Socket.Id} all subscription successfully resubscribed on reconnected socket.");
return true;
}
@@ -401,36 +417,39 @@ namespace CryptoExchange.Net.Sockets
/// Close the connection
/// </summary>
/// <returns></returns>
public async Task Close()
public async Task CloseAsync()
{
Connected = false;
ShouldReconnect = false;
if (socketClient.sockets.ContainsKey(Socket.Id))
socketClient.sockets.TryRemove(Socket.Id, out _);
await Socket.Close().ConfigureAwait(false);
await Socket.CloseAsync().ConfigureAwait(false);
Socket.Dispose();
}
/// <summary>
/// Close the subscription
/// Close a subscription on this connection. If all subscriptions on this connection are closed the connection gets closed as well
/// </summary>
/// <param name="subscription">Subscription to close</param>
/// <returns></returns>
public async Task Close(SocketSubscription subscription)
public async Task CloseAsync(SocketSubscription subscription)
{
if (!Socket.IsOpen)
return;
if (subscription.Confirmed)
await socketClient.Unsubscribe(this, subscription).ConfigureAwait(false);
await socketClient.UnsubscribeAsync(this, subscription).ConfigureAwait(false);
var shouldCloseWrapper = false;
lock (handlersLock)
shouldCloseWrapper = handlers.Count(r => r.UserSubscription && subscription != r) == 0;
var shouldCloseConnection = false;
lock (subscriptionLock)
shouldCloseConnection = !subscriptions.Any(r => r.UserSubscription && subscription != r);
if (shouldCloseWrapper)
await Close().ConfigureAwait(false);
if (shouldCloseConnection)
await CloseAsync().ConfigureAwait(false);
lock (handlersLock)
handlers.Remove(subscription);
lock (subscriptionLock)
subscriptions.Remove(subscription);
}
}
@@ -1,5 +1,4 @@
using System;
using Newtonsoft.Json.Linq;
namespace CryptoExchange.Net.Sockets
{
@@ -16,7 +15,7 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// Message handlers for this subscription. Should return true if the message is handled and should not be distributed to the other handlers
/// </summary>
public Action<SocketConnection, JToken> MessageHandler { get; set; }
public Action<MessageEvent> MessageHandler { get; set; }
/// <summary>
/// Request object
@@ -36,7 +35,7 @@ namespace CryptoExchange.Net.Sockets
/// </summary>
public bool Confirmed { get; set; }
private SocketSubscription(object? request, string? identifier, bool userSubscription, Action<SocketConnection, JToken> dataHandler)
private SocketSubscription(object? request, string? identifier, bool userSubscription, Action<MessageEvent> dataHandler)
{
UserSubscription = userSubscription;
MessageHandler = dataHandler;
@@ -52,7 +51,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="dataHandler"></param>
/// <returns></returns>
public static SocketSubscription CreateForRequest(object request, bool userSubscription,
Action<SocketConnection, JToken> dataHandler)
Action<MessageEvent> dataHandler)
{
return new SocketSubscription(request, null, userSubscription, dataHandler);
}
@@ -65,7 +64,7 @@ namespace CryptoExchange.Net.Sockets
/// <param name="dataHandler"></param>
/// <returns></returns>
public static SocketSubscription CreateForIdentifier(string identifier, bool userSubscription,
Action<SocketConnection, JToken> dataHandler)
Action<MessageEvent> dataHandler)
{
return new SocketSubscription(null, identifier, userSubscription, dataHandler);
}
@@ -4,7 +4,7 @@ using System.Threading.Tasks;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// Subscription
/// Subscription to a data stream
/// </summary>
public class UpdateSubscription
{
@@ -21,7 +21,9 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting
/// Event when the connection is restored. Timespan parameter indicates the time the socket has been offline for before reconnecting.
/// Note that when the executing code is suspended and resumed at a later period (for example laptop going to sleep) the disconnect time will be incorrect as the diconnect
/// will only be detected after resuming. This will lead to an incorrect disconnected timespan.
/// </summary>
public event Action<TimeSpan> ConnectionRestored
{
@@ -30,7 +32,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Event when the connection to the server is paused. No operations can be performed while paused
/// Event when the connection to the server is paused based on a server indication. No operations can be performed while paused
/// </summary>
public event Action ActivityPaused
{
@@ -39,7 +41,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Event when the connection to the server is unpaused
/// Event when the connection to the server is unpaused after being paused
/// </summary>
public event Action ActivityUnpaused
{
@@ -48,7 +50,7 @@ namespace CryptoExchange.Net.Sockets
}
/// <summary>
/// Event when an exception happened
/// Event when an exception happens during the handling of the data
/// </summary>
public event Action<Exception> Exception
{
@@ -64,8 +66,8 @@ namespace CryptoExchange.Net.Sockets
/// <summary>
/// ctor
/// </summary>
/// <param name="connection"></param>
/// <param name="subscription"></param>
/// <param name="connection">The socket connection the subscription is on</param>
/// <param name="subscription">The subscription</param>
public UpdateSubscription(SocketConnection connection, SocketSubscription subscription)
{
this.connection = connection;
@@ -76,18 +78,18 @@ namespace CryptoExchange.Net.Sockets
/// Close the subscription
/// </summary>
/// <returns></returns>
public async Task Close()
public Task CloseAsync()
{
await connection.Close(subscription).ConfigureAwait(false);
return connection.CloseAsync(subscription);
}
/// <summary>
/// Close the socket to cause a reconnect
/// </summary>
/// <returns></returns>
internal Task Reconnect()
internal Task ReconnectAsync()
{
return connection.Socket.Close();
return connection.Socket.CloseAsync();
}
}
}
@@ -5,20 +5,20 @@ using CryptoExchange.Net.Logging;
namespace CryptoExchange.Net.Sockets
{
/// <summary>
/// Factory implementation
/// Default weboscket factory implementation
/// </summary>
public class WebsocketFactory : IWebsocketFactory
{
/// <inheritdoc />
public IWebsocket CreateWebsocket(Log log, string url)
{
return new BaseSocket(log, url);
return new CryptoExchangeWebSocketClient(log, url);
}
/// <inheritdoc />
public IWebsocket CreateWebsocket(Log log, string url, IDictionary<string, string> cookies, IDictionary<string, string> headers)
{
return new BaseSocket(log, url, cookies, headers);
return new CryptoExchangeWebSocketClient(log, url, cookies, headers);
}
}
}