private void SocketOnClose(CoinExStream stream) { log.Write(LogVerbosity.Debug, $"Socket {stream.StreamResult.StreamId} closed event"); if (stream.TryReconnect) { log.Write(LogVerbosity.Info, $"Socket {stream.StreamResult.StreamId} Connection lost, going to try to reconnect"); Task.Run(() => { Thread.Sleep(reconnectInterval); if (!stream.Socket.Connect().Result) { log.Write(LogVerbosity.Debug, $"Socket {stream.StreamResult.StreamId} failed to reconnect"); return; // Connect() should result in a SocketClosed event so we end up here again } log.Write(LogVerbosity.Info, $"Socket {stream.StreamResult.StreamId} Reconnected"); if (stream.Request != null) { var resubResult = Subscribe(stream, stream.Request, true).Result; if (!resubResult.Success) { log.Write(LogVerbosity.Info, $"Socket {stream.StreamResult.StreamId} failed to resubscribe, closing socket and trying again"); stream.Close(true).Wait(); } else { log.Write(LogVerbosity.Info, $"Socket {stream.StreamResult.StreamId} resubscribed reconnected socket"); } } }); } else { log.Write(LogVerbosity.Info, $"Socket {stream.StreamResult.StreamId} closed"); lock (subscriptions) if (subscriptions.Contains(stream.Subscription)) { subscriptions.Remove(stream.Subscription); } stream.StreamResult.InvokeClosed(); stream.Socket.Dispose(); lock (sockets) sockets.Remove(stream); } }
private async Task <CallResult <CoinExStreamSubscription> > Subscribe(CoinExStream stream, CoinExSocketRequest request, bool resubscribing) { if (stream.Authenticated) { var auth = await Authenticate(stream).ConfigureAwait(false); if (!auth.Success) { return(new CallResult <CoinExStreamSubscription>(null, auth.Error)); } } if (!resubscribing) // Only add the message handler once, is already done if resubscribing { stream.Socket.OnMessage += (msg) => OnMessage(stream.StreamResult.StreamId, msg); } var subConfirm = await Query <CoinExSocketRequestResponseMessage>(stream, request).ConfigureAwait(false); if (subConfirm.Success) { stream.Request = request; stream.Subscription.StreamId = stream.StreamResult.StreamId; stream.TryReconnect = true; lock (subscriptions) if (!subscriptions.Contains(stream.Subscription)) { subscriptions.Add(stream.Subscription); } log.Write(LogVerbosity.Info, $"Subscription {stream.Subscription.StreamId} successful"); } else { log.Write(LogVerbosity.Info, $"Failed to subscribe {stream.Subscription.StreamId}: {subConfirm.Error}"); if (!resubscribing) // If we're just trying to initialy subscribe we dont need to reconnect if we failed subbing, so close it here { await stream.Close().ConfigureAwait(false); } } return(new CallResult <CoinExStreamSubscription>(stream.StreamResult, subConfirm.Error)); }