internal void Connect(long connectionTimeout, ConnectionTimeoutAction timeoutAction, long networkTimeout, NetworkUnavailableAction networkUnavailableAction) { try { // TODO: Add 'connecting_in' event Log.Info(Constants.LOG_NAME, $"Connecting to: {_url}"); ChangeState(ConnectionState.Initialized); _allowReconnect = true; this.connectionTimeout = connectionTimeout; this.connectionTimeoutAction = timeoutAction; this.networkTimeout = networkTimeout; this.networkUnavailableAction = networkUnavailableAction; timeoutTimer = new System.Timers.Timer(connectionTimeout); networkTimer = new System.Timers.Timer(networkTimeout); _websocket = new WebSocket(_url) { EnableAutoSendPing = true, AutoSendPingInterval = 8 }; _websocket.Opened += websocket_Opened; _websocket.Error += websocket_Error; _websocket.Closed += websocket_Closed; _websocket.MessageReceived += websocket_MessageReceived; ChangeState(ConnectionState.Connecting); if (connectionTimeout != -1) // If the user provided a timeout value { StartTimeoutCountdown(); } // Websocket does not notice when the internet dies, this is a temp workaround until there's a fix if (networkTimeout != -1) { StartCheckForInternetConnection(); } _websocket.Open(); reconnectAlreadyInProgress = false; } catch (Exception e) { Log.Error(Constants.LOG_NAME, $"{e.Message}"); } }
/// <summary> /// Start the connection to the Pusher Server. When completed, the <see cref="Connected"/> event will fire. /// <param name="connectionTimeout">Time in milliseconds that if connection isn't established should timeout. Recommended is 10000ms.</param> /// <param name="timeoutAction">The action that should happen when the connection times out.</param> /// <paramref name="networkTimeout">Time in milliseconds that the network availability checker should repeatedly check for network availability. Recommended is 20000ms.</paramref> /// <paramref name="networkUnavailableAction">The action that should happen when when the network is unavailable.</paramref> /// </summary> public Task ConnectAsync(long connectionTimeout = -1, ConnectionTimeoutAction timeoutAction = ConnectionTimeoutAction.Ignore, long networkTimeout = -1, NetworkUnavailableAction networkUnavailableAction = NetworkUnavailableAction.Ignore) { // Prevent multiple concurrent connections lock (_lockingObject) { return(Task.Run(() => { // Ensure we only ever attempt to connect once if (_connection != null) { Log.Warn(Constants.LOG_NAME, ErrorConstants.ConnectionAlreadyConnected); return; } var scheme = _options.Encrypted ? Constants.SECURE_SCHEMA : Constants.INSECURE_SCHEMA; // TODO: Fallback to secure? var url = $"{scheme}{_options.Host}/app/{_applicationKey}?protocol={Settings.ProtocolVersion}&client={Settings.ClientName}&version={Settings.VersionNumber}"; _connection = new Connection(this, url); _connection.Connect(connectionTimeout, timeoutAction, networkTimeout, networkUnavailableAction); })); } }