private void Reconnect() { log.Debug("Trying to reconnect websocket."); if (isConnecting) { return; } Stop(); //close current connection log.Debug("Trying to close old connection."); Close(); isConnecting = true; log.Debug("Start getting request to obtain ws address."); var request = HttpWebClientHelper.CreateRequest(sdkMetadata, string.Format(FluxApiData.WebSocketUrl, ProjectId, reason), UserCookies); request.Method = "GET"; request.Headers.Add("projectId", ProjectId); try { var response = HttpWebClientHelper.GetResponse(request); if (response.StatusCode == HttpStatusCode.OK) { var wsUrl = DataSerializer.Deserialize <WebSocketAddress>(StreamUtils.GetDecompressedResponseStream(response)); log.Debug("Connecting to Flux wss: {0}", wsUrl.Address); webSocket = new WebSocketSharp.WebSocket(wsUrl.Address); webSocket.WaitTime = TimeSpan.FromHours(12); foreach (var cookie in UserCookies) { WebSocketSharp.Net.Cookie wsCookie = new WebSocketSharp.Net.Cookie(cookie.CookieName, cookie.CookieValue, cookie.CookieDomain); webSocket.SetCookie(wsCookie); } webSocket.OnMessage += WebSocket_OnMessage; webSocket.OnClose += WebSocket_Closed; webSocket.OnOpen += WebSocket_Opened; webSocket.OnError += WebSocket_OnError; webSocket.ConnectAsync(); //start timer RestartConnectionTimer(); } } catch (Exception ex) { log.Error(ex); webSocketState = FluxWebSocketStates.Reconnecting; if (ex is WebException || ex is Exceptions.ConnectionFailureException || ex is Exceptions.ServerUnavailableException) { var webException = ex as WebException; if (webException != null) { var webResponse = (HttpWebResponse)webException.Response; if (webResponse != null) { Close(); return; } } log.Error("Error initializing WebSocket."); isConnecting = false; if (reconnectDelay * 2 < MAX_DELAY) { reconnectDelay *= 2; } else { reconnectDelay = MAX_DELAY; } RetryReconnect(); } else { log.Error("Unsupported exception was caught. Websocket will be closed."); Close(); } } }