/// <summary> /// Initialize the web socket connection to the live data server /// </summary> public void Initialize() { _initialized = true; _builder = new UriBuilder(new Uri(_liveDataUrl)) { Port = _liveDataPort }; _ws = new WebSocket(_builder.ToString()); var connectionRetryAttempts = 0; var timeStamp = (int)Time.TimeStamp(); var hash = Api.CreateSecureHash(timeStamp, _token); _ws.SetCookie(new Cookie("Timestamp", timeStamp.ToString())); _ws.SetCookie(new Cookie("hash", hash)); _ws.SetCookie(new Cookie("uid", _userId.ToString())); // Message received from server _ws.OnMessage += (sender, e) => { lock (_locker) { IEnumerable <BaseData> baseDatas = new List <BaseData>(); try { baseDatas = BaseData.DeserializeMessage(e.Data); } catch { Log.Error("ApiWebSocketConnection.OnMessage(): An error was received from the server: {0}", e.Data); } foreach (var baseData in baseDatas) { _baseDataFromServer.Enqueue(baseData); } } }; // Error has in web socket connection _ws.OnError += (sender, e) => { Log.Error("WebSocketConnection.Initialize(): Web socket connection error: {0}", e.Message); if (!_ws.IsAlive && connectionRetryAttempts < MaxRetryAttempts) { Log.Trace( "WebSocketConnection.Initialize(): Attempting to reconnect {0}/{1}", connectionRetryAttempts, MaxRetryAttempts); connectionRetryAttempts++; _ws.Connect(); } else { Log.Trace( "WebSocketConnection.Initialize(): Could not reconnect to web socket server. " + "Closing web socket."); if (_updateSubscriptions != null) { _updateSubscriptions -= UpdateSubscriptions; } _updateSubscriptions = null; } }; // Connection was closed _ws.OnClose += (sender, e) => { Log.Trace( "WebSocketConnection.Initialize(): Web socket connection closed: {0}, {1}", e.Code, e.Reason); if (!_ws.IsAlive && connectionRetryAttempts < MaxRetryAttempts && e.Code == (ushort)CloseStatusCode.Abnormal) { Log.Error( "WebSocketConnection.Initialize(): Web socket was closed abnormally. " + "Attempting to reconnect {0}/{1}", connectionRetryAttempts, MaxRetryAttempts); connectionRetryAttempts++; _ws.Connect(); } else { Log.Trace( "WebSocketConnection.Initialize(): Could not reconnect to web socket server. " + "Closing web socket."); if (_updateSubscriptions != null) { _updateSubscriptions -= UpdateSubscriptions; } _updateSubscriptions = null; } }; // Connection opened _ws.OnOpen += (sender, e) => { SendSubscription(); connectionRetryAttempts = 0; }; _updateSubscriptions += UpdateSubscriptions; _ws.Connect(); }