/// <summary>
        /// Restores session or tries to establish a new one.
        /// Invokes <see cref="OnConnectionSuccess"/> or <see cref="OnConnectionFailure"/>.
        /// </summary>
        /// <returns></returns>
        public async Task <AuthenticationResponse> ConnectAsync()
        {
            AuthenticationResponse response = await RestoreTokenAsync();

            switch (response)
            {
            case AuthenticationResponse.Authenticated:
                OnConnectionSuccess?.Invoke();
                break;

            case AuthenticationResponse.NewAccountCreated:
                OnNewAccountCreated?.Invoke();
                OnConnectionSuccess?.Invoke();
                break;

            case AuthenticationResponse.Error:
                OnConnectionFailure?.Invoke();
                break;

            default:
                Debug.LogError("Unhandled response received: " + response);
                break;
            }
            return(response);
        }
        private async Task StartAsync()
        {
            try
            {
                OnSubMessage?.Invoke($"正在连接{_clientConfig.Url}....", "重要");
                ClientWebSocket = new ClientWebSocket();
                var uri = new Uri(_clientConfig.Url);
                _cancellationToken = new CancellationToken();
                await ClientWebSocket.ConnectAsync(uri, _cancellationToken);

                OnSubMessage?.Invoke("连接成功", "重要");
                if (!_isListening)
                {
                    StartListeningAsync();
                }
                _isManualClose = false;
                OnConnectionSuccess?.Invoke();
                _reconnectionNumber = 0;
            }
            catch (Exception exception)
            {
                await StopAsync(false);

                OnSubMessage?.Invoke("连接失败", "重要");
                OnException?.Invoke(exception);
                OnConnectionFail?.Invoke();
            }
        }
Example #3
0
        private void OnSteamClientConnected(SteamClient.ConnectedCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                OnConnectionFailure?.Invoke(this, string.Format("Unable to connect to Steam: {0}", callback.Result));

                Disconnect();
                return;
            }

            OnConnectionSuccess?.Invoke(this, string.Format("Connected to Steam! Logging in '{0}'...", m_SteamUserName));

            byte[] sentryHash = null;
            if (File.Exists(Settings.Default.SentryFileLocation))
            {
                // if we have a saved sentry file, read and sha-1 hash it
                byte[] sentryFile = File.ReadAllBytes(Settings.Default.SentryFileLocation);
                sentryHash = CryptoHelper.SHAHash(sentryFile);
            }

            m_steamUser.LogOn(new SteamUser.LogOnDetails
            {
                Username = m_SteamUserName,
                Password = m_SteamPassword.ToPlainText(),

                // this value will be null (which is the default) for our first logon attempt
                AuthCode = m_AuthCode,

                // if the account is using 2-factor auth, we'll provide the two factor code instead
                // this will also be null on our first logon attempt
                TwoFactorCode = m_TwoFactorAuth,

                // our subsequent logons use the hash of the sentry file as proof of ownership of the file
                // this will also be null for our first (no authcode) and second (authcode only) logon attempts
                SentryFileHash = sentryHash,
            });
        }
Example #4
0
        public virtual void Connect(BTPeer peer, int numberOfRetries = 5)
        {
            Task.Run(async() =>
            {
                try
                {
                    socket = peer.Device.CreateRfcommSocketToServiceRecord(BluetoothServer.ServiceUUID);
                    await Task.Delay(100);
                    socket.Connect();
                    await Task.Delay(250);

                    if (socket.IsConnected)
                    {
                        Log.Debug(_tag, $"Client: Connection accepted to {socket.RemoteDevice.Address}.");
                        OnConnectionSuccess?.Invoke(this, EventArgs.Empty);
                        IsConnected = true;
                    }
                    else
                    {
                        OnConnectionFailure?.Invoke(this, EventArgs.Empty);
                        IsConnected = false;
                        if (numberOfRetries > 0)
                        {
                            Log.Debug(_tag, $"Client: Connection unsuccessful; retrying in {SocketTimeout} ms.");
                            await Task.Delay(SocketTimeout)
                            .ContinueWith((_) => { Connect(peer, numberOfRetries - 1); })
                            .ConfigureAwait(false);
                        }
                        else
                        {
                            Log.Debug(_tag, "Client: Connection unsuccessful, retry limit exhausted.");
                        }
                        return;
                    }

                    inStream  = new DataInputStream(socket.InputStream);
                    outStream = new DataOutputStream(socket.OutputStream);

                    BluetoothCore.RunSendingLooper(this);

                    Task.Delay(500)
                    .ContinueWith(_ =>
                                  SendMessage(new Message(MsgType.Notify,
                                                          $"{CONFIRM_AS_CLIENT}{NEXT}{socket.RemoteDevice.Address}")))
                    .LaunchAsOrphan();

                    //await Task.Delay(100);
                    var ListeningLoop = Task.Run((Action)Listen); // When finished, *should* mean that it's received its stop signal and is thus ready to close.

                    //foreach (var teammate in HeyYou.MyTeammates.TeamMembers)
                    //{
                    //    var teamMate = teammate as CommsContact;
                    //    if (teamMate == null) continue;
                    //    if (teamMate.IPaddress == socket.RemoteDevice.Address) continue; // Don't bother suggesting themselves as a teammate!
                    //    SendMessage(new Message(MsgType.Notify, $"{SUGGEST_TEAMMATE}{NEXT}{teamMate.IPaddress}"));
                    //}

                    await ListeningLoop;
                }
                catch (Exception e)
                {
                    Log.Debug(_tag, e.ToString());
                }
                finally
                {
                    Log.Debug(_tag, "Closing client connection.");
                    //socket.Close();
                    //IsConnected = false;
                    Disconnect();
                }
            });
        }