Beispiel #1
0
        /// <summary>
        /// Initiates logging in with the current <see cref="IProvider"/> registered in the <see cref="ProviderManager"/>.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task LoginAsync()
        {
            if (UserDetails != null)
            {
                return;
            }

            var provider = ProviderManager.Instance.GlobalProvider;

            if (provider != null)
            {
                await provider.LoginAsync();

                if (provider.State == ProviderState.SignedIn)
                {
                    // TODO: include user details?
                    LoginCompleted?.Invoke(this, new EventArgs());
                }
                else
                {
                    LoginFailed?.Invoke(this, new EventArgs());
                }

                LoadData();
            }
        }
Beispiel #2
0
        private async void LoginAsync(PasswordBox passwordBox)
        {
            try
            {
                IsLoading = true;
                Boolean result = await _service.LoginAsync(UserName, passwordBox.Password);

                if (result)
                {
                    LoginSucceeded?.Invoke(this, EventArgs.Empty);
                }
                else
                {
                    LoginFailed?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception ex) when(ex is NetworkException || ex is HttpRequestException)
            {
                OnMessageApplication($"Unexpected error occured! ({ex.Message})");
            }
            finally
            {
                IsLoading = false;
            }
        }
        /// <summary>
        /// Initiates logging in with the current <see cref="IProvider"/> registered in the <see cref="ProviderManager"/>.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task LoginAsync()
        {
            if (UserDetails != null)
            {
                return;
            }

            var provider = ProviderManager.Instance.GlobalProvider;

            if (provider != null)
            {
                try
                {
                    await provider.LoginAsync();

                    if (provider.State == ProviderState.SignedIn)
                    {
                        // TODO: include user details?
                        LoginCompleted?.Invoke(this, new EventArgs());

                        LoadData();
                    }
                    else
                    {
                        LoginFailed?.Invoke(this, new LoginFailedEventArgs(new TimeoutException("Login did not complete.")));
                    }
                }
                catch (Exception e)
                {
                    LoginFailed?.Invoke(this, new LoginFailedEventArgs(e));
                }
            }
        }
Beispiel #4
0
        private async void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var user = await Models.User.Login(PhoneTextBox.Text, CodePasswordBox.Password);

                if (user != null)
                {
                    LoginSucceed?.Invoke(this, new LoginEventArgs()
                    {
                        user = user, isSuccess = true
                    });                                                                                //把按钮自身作为参数传递
                }
                else
                {
                    LoginFailed?.Invoke(this, new LoginEventArgs()
                    {
                        isSuccess = false
                    });
                }
            }
            catch (Exception excep)
            {
                LoginFailed?.Invoke(this, new LoginEventArgs()
                {
                    isSuccess = false, message = excep.Message
                });
            }
        }
        private async void Login()
        {
            RaiseCanExecuteChanged();

            SimpleUser user;

            try
            {
                using (ProgressProvider.StartProgress())
                {
                    user = await _signalHelperFacade.LoginSignalHelper.Login(Username, Password).ConfigureAwait(true);
                }
            }
            catch (LoginFailedException e)
            {
                LoginFailed?.Invoke(new LoginFailedEventArgs(e.Message));
                return;
            }
            finally
            {
                RaiseCanExecuteChanged();
            }

            LoggedIn = true;
            LoginSucceeded?.Invoke(new LoginSucceededEventArgs(user));

            Application.Current.Dispatcher.Invoke(RaiseCanExecuteChanged);
        }
Beispiel #6
0
        public void SetResult(int status)
        {
            Authenticated = status == 0;
            try
            {
                switch (status)
                {
                case LOGIN_SUCCESS:
                    LoginSuccess?.Invoke(this, EventArgs.Empty);
                    return;

                case LOGIN_INVALID:
                    LoginFailed?.Invoke(this, new LoginFailedEventArgs(false));
                    return;

                case LOGIN_BANNED:
                    LoginFailed?.Invoke(this, new LoginFailedEventArgs(true));
                    return;
                }
            }
            finally
            {
                Interlocked.CompareExchange(ref activeAuthRequest, 0, 1);
            }
        }
Beispiel #7
0
 private void RaiseLoginFailed(LoginResult loginResult)
 {
     if (LoginFailed != null)
     {
         LoginFailed.Invoke(this, loginResult);
     }
 }
Beispiel #8
0
 private void ConnectFailed( )
 {
     ConnectFailedCount++;
     Interlocked.Exchange(ref isConnecting, 0);
     LoginFailed?.Invoke(ConnectFailedCount);
     LogNet?.WriteDebug(ToString( ), "Connected Failed, Times: " + ConnectFailedCount);
 }
Beispiel #9
0
        public async void Login()
        {
            Busy = true;

            if (string.IsNullOrEmpty(Email) || string.IsNullOrEmpty(Password))
            {
                LoginFailed?.Invoke(this, "Email and Password are required.");

                Busy = false;

                return;
            }

            var result = await Services.Host.AuthService.Authenticate(Email, Password);

            if (result.Success)
            {
                LoginSuccess?.Invoke(this, EventArgs.Empty);

                Busy = false;

                return;
            }

            LoginFailed?.Invoke(this, result.error_description);

            Busy = false;
        }
Beispiel #10
0
        private async void LoadData()
        {
            var provider = ProviderManager.Instance.GlobalProvider;

            if (provider == null)
            {
                return;
            }

            if (provider.State == ProviderState.SignedIn)
            {
                try
                {
                    // https://github.com/microsoftgraph/microsoft-graph-toolkit/blob/master/src/components/mgt-login/mgt-login.ts#L139
                    // TODO: Batch with photo request later? https://github.com/microsoftgraph/msgraph-sdk-dotnet-core/issues/29
                    UserDetails = await provider.Graph.Me.Request().GetAsync();
                }
                catch (Exception e)
                {
                    LoginFailed?.Invoke(this, new LoginFailedEventArgs(e));
                }
            }
            else if (provider.State == ProviderState.SignedOut)
            {
                UserDetails = null; // What if this was user provided? Should we not hook into these events then?
            }
            else
            {
                // Provider in Loading state
                return;
            }

            IsLoading = false;
        }
        public async Task <bool> LoginUser(string userName, string password)
        {
            var result = false;

            try
            {
                var api = new IdentityApi(
                    "https://localhost:6001",
                    await TokenService.Instance.GetAccessTokenAsync());

                var validUser = await api.ValidateUser(userName, password);

                if (validUser)
                {
                    var authUser = await api.GetAuthenticatedUser(userName);

                    if (authUser != null)
                    {
                        this.CurrentPrincipal = authUser;
                        LoggedIn?.Invoke(this, EventArgs.Empty);
                        result = true;
                    }
                }
                else
                {
                    LoginFailed?.Invoke(this, EventArgs.Empty);
                }
            }
            catch (Exception e)
            {
                this.Log().LogError(e.Message);
            }

            return(result);
        }
Beispiel #12
0
        /// <summary>
        /// 登陆到百度
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>返回登陆是否成功</returns>
        /// <remarks>no throw, return false if failed</remarks>
        public bool Login(string username, string password)
        {
            Tracer.GlobalTracer.TraceInfo("BaiduOAuth.Login called: username="******", password=*");
            _username = username;
            _password = password;
            try
            {
                // #1 HTTP request: token request
                _get_token();

                // #2 HTTP request: login check
                var captcha_data = _v2_api__logincheck(_token, username);
                //需要验证码并且验证码为空时,引发CaptchaRequiredException
                if (!string.IsNullOrEmpty(captcha_data.codestring) && _verifycode == null)
                {
                    _codestring = captcha_data.codestring;
                    _vcodetype  = captcha_data.vcodetype;
                    LoginCaptchaRequired?.Invoke();
                    throw new CaptchaRequiredException();
                }

                // #3 HTTP request: get public key (RSA password encryption)
                var rsa_key = _v2_getpublickey(_token, _get_guid());

                // #4 HTTP request: post login
                var login_result = _v2_api__login(_token, _codestring, _get_guid(), username, password, rsa_key.key, rsa_key.pubkey, _verifycode);
                //对登陆结果返回的验证码字段进行赋值
                if (!string.IsNullOrEmpty(login_result.vcodetype))
                {
                    _vcodetype = login_result.vcodetype;
                }
                if (!string.IsNullOrEmpty(login_result.codestring))
                {
                    _codestring = login_result.codestring;
                }
                switch (login_result.errno)
                {
                case "0":
                    //登陆成功
                    LoginSucceeded?.Invoke();
                    return(true);

                case "257":
                    LoginCaptchaRequired?.Invoke();
                    throw new CaptchaRequiredException();

                default:
                    _failed_code   = int.Parse(login_result.errno);
                    _failed_reason = "";
                    throw new LoginFailedException("Login failed with response code " + login_result.errno);
                }
            }
            catch (Exception ex)
            {
                Tracer.GlobalTracer.TraceError(ex);
                LoginFailed?.Invoke();
                return(false);
            }
        }
Beispiel #13
0
        public async Task LoginAsync()
        {
            try
            {
                var opts = new OidcClientOptions
                {
                    Authority    = m_Authority,
                    ClientId     = m_ClientId,
                    ClientSecret = m_ClientSecret,
                    RedirectUri  = m_RedirectUrl,
                    Scope        = m_Scope,
                    LoadProfile  = m_LoadProfile,
                    Flow         = OidcClientOptions.AuthenticationFlow.AuthorizationCode,
                    ResponseMode = OidcClientOptions.AuthorizeResponseMode.Redirect,
                    Policy       = new Policy()
                    {
                        RequireAuthorizationCodeHash = false,
                        RequireAccessTokenHash       = false
                    }
                };

                var client = new OidcClient(opts);

                var loginRequest = new LoginRequest();

                var state = await client.PrepareLoginAsync();

                var authData = GetUserData();

                LoginResult loginRes = null;

                if (authData.StayLoggedIn)
                {
                    loginRes = await Login(client, state, true, authData.StayLoggedIn);
                }

                if (loginRes?.User == null)
                {
                    loginRes = await Login(client, state, false, authData.StayLoggedIn);
                }

                if (loginRes.User != null)
                {
                    LoggedIn?.Invoke(loginRes.User.Identity?.Name);
                }
                else
                {
                    throw new Exception(loginRes.Error);
                }
            }
            catch (Exception ex)
            {
                LoginFailed?.Invoke();
                throw new LoginFailedException(ex);
            }
        }
        private void OnClick_btnLogin()
        {
            bool succeedLogin = LoginService.LoadUser(Address, Password);

            if (succeedLogin)
            {
                LoginSucceed?.Invoke(this, EventArgs.Empty);
            }
            else
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
            }
        }
Beispiel #15
0
        public void Login()
        {
            string homepageResponse = httpManager.Get("http://www.darkorbit.com/");
            Match  match            = Regex.Match(homepageResponse, "class=\"bgcdw_login_form\" action=\"(.*)\">");

            if (!match.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            string loginResponse = httpManager.Post(WebUtility.HtmlDecode(match.Groups[1].ToString()), $"username={Username}&password={Password}");

            match = Regex.Match(httpManager.lastURL, "https://(.*).darkorbit.bigpoint.com");

            if (!match.Success)
            {
                match = Regex.Match(httpManager.lastURL, "https://(.*).darkorbit.com");
            }
            if (!match.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            Server = match.Groups[1].ToString();

            string mapResponse = httpManager.Get($"{match.Value}/indexInternal.es?action=internalMapRevolution");

            match = Regex.Match(mapResponse, "{\"pid\":([0-9]+),\"uid\":([0-9]+)[\\w,\":]+sid\":\"([0-9a-z]+)\"");

            Match pid = Regex.Match(mapResponse, "basePath\": \"spacemap\",\"pid\": \"([0-9]+)");

            if (!match.Success || !pid.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            InstanceID = int.Parse(pid.Groups[1].ToString());
            UserID     = int.Parse(match.Groups[2].ToString());
            SID        = match.Groups[3].ToString();
            match      = Regex.Match(mapResponse, "mapID\": \"([0-9]*)\"");
            Map        = int.Parse(match.Groups[1].ToString());

            LoginSucceed?.Invoke(this, EventArgs.Empty);
        }
Beispiel #16
0
        public void OnEvent(SdkEvent sdkEvent)
        {
            if (sdkEvent.Event.Equals("Connected"))
            {
                Connected?.Invoke(this);
            }
            else if (sdkEvent.Event.Equals("ConnectionFailed"))
            {
                ConnectionFailed?.Invoke(this, sdkEvent.GetEventArgs <ConnectionFailedEventArgs>());
            }
            else if (sdkEvent.Event.Equals("Disconnected"))
            {
                Disconnected?.Invoke(this);
            }
            else if (sdkEvent.Event.Equals("LoginSuccess"))
            {
                LoginSuccess?.Invoke(this, sdkEvent.GetEventArgs <LoginSuccessEventArgs>());
            }
            else if (sdkEvent.Event.Equals("LoginFailed"))
            {
                LoginFailed?.Invoke(this, sdkEvent.GetEventArgs <LoginFailedEventArgs>());
            }
            else if (sdkEvent.Event.Equals("RefreshTokenSuccess"))
            {
                RefreshTokenSuccess?.Invoke(this, sdkEvent.GetEventArgs <RefreshTokenSuccessEventArgs>());
            }
            else if (sdkEvent.Event.Equals("RefreshTokenFailed"))
            {
                RefreshTokenFailed?.Invoke(this, sdkEvent.GetEventArgs <RefreshTokenFailedEventArgs>());
            }
            else if (sdkEvent.Event.Equals("OneTimeKeyGenerated"))
            {
                OneTimeKeyGenerated?.Invoke(this, sdkEvent.GetEventArgs <OneTimeKeyGeneratedEventArgs>());
            }
            else if (sdkEvent.Event.Equals("IncomingCall"))
            {
                var eventArgs = sdkEvent.GetEventArgs <IncomingCallEventArgs>();
                eventArgs.Call = GetIncomingCall(eventArgs.callId);

                IncomingCall?.Invoke(this, eventArgs);
            }
            else
            {
                Debug.LogError($"Unknown Event '{sdkEvent.Event}'");
            }
        }
Beispiel #17
0
        private void CustomLoginControl_LoginAttempt(object sender, LoginEventArgs e)
        {
            var user = Users.Where(x => x.CheckLogin(e.Login, e.Password)).SingleOrDefault();

            if (user == null)
            {
                LoginFailed?.Invoke(this, new LoginFailureEventArgs()
                {
                    Errors = new List <LoginFailureEventArgs.LoginError>()
                    {
                        new LoginFailureEventArgs.LoginError()
                        {
                            Field        = LoginFields.All,
                            ErrorMessage = "Wrong username or password"
                        }
                    }
                });
            }
            else
            {
                LoginSuccess?.Invoke(this, EventArgs.Empty);
            }
        }
Beispiel #18
0
        public void CostomLoginControl_LoginAttempt(object sender, LoginEventArgs e)
        {
            var user = users.Where(x => x.CheckLogin(e.Login, e.Password.ToString())).SingleOrDefault();

            if (user == null)
            {
                LoginFailed?.Invoke(this, new LoginFailureEventArgs()
                {
                    Errors = new List <LoginFailureEventArgs.LoginError>()
                    {
                        new LoginFailureEventArgs.LoginError()
                        {
                            Field        = LoginFields.All,
                            ErrorMessage = "Zły login lub hasło"
                        }
                    }
                });
            }
            else
            {
                LoginSucces?.Invoke(this, EventArgs.Empty);
                this.Close();
            }
        }
Beispiel #19
0
 private void OnLoginFailed()
 {
     LoginFailed?.Invoke(this, EventArgs.Empty);
 }
        private void ThreadLogin()
        {
            lock (lock_connecting)
            {
                if (IsClientConnecting)
                {
                    return;
                }
                IsClientConnecting = true;
            }


            if (ConnectFailedCount == 0)
            {
                // English Version : Connecting Server...
                MessageAlerts?.Invoke("正在连接服务器...");
            }
            else
            {
                int count = 10;
                while (count > 0)
                {
                    if (IsQuie)
                    {
                        return;
                    }
                    // English Version : Disconnected, wait [count--] second to restart
                    MessageAlerts?.Invoke("连接断开,等待" + count-- + "秒后重新连接");
                    Thread.Sleep(1000);
                }
                MessageAlerts?.Invoke("正在尝试第" + ConnectFailedCount + "次连接服务器...");
            }


            stateone.HeartTime = DateTime.Now;
            LogNet?.WriteDebug(ToString( ), "Begin Connect Server, Times: " + ConnectFailedCount);

            OperateResult <Socket> connectResult = CreateSocketAndConnect(EndPointServer, 10000);

            if (!connectResult.IsSuccess)
            {
                ConnectFailedCount++;
                IsClientConnecting = false;
                LoginFailed?.Invoke(ConnectFailedCount);
                LogNet?.WriteDebug(ToString( ), "Connected Failed, Times: " + ConnectFailedCount);
                // 连接失败,重新连接服务器
                ReconnectServer( );
                return;
            }



            // 连接成功,发送数据信息
            OperateResult sendResult = SendStringAndCheckReceive(connectResult.Content, 1, ClientAlias);

            if (!sendResult.IsSuccess)
            {
                ConnectFailedCount++;
                IsClientConnecting = false;
                LogNet?.WriteDebug(ToString( ), "Login Server Failed, Times: " + ConnectFailedCount);
                LoginFailed?.Invoke(ConnectFailedCount);
                // 连接失败,重新连接服务器
                ReconnectServer( );
                return;
            }

            // 登录成功
            ConnectFailedCount  = 0;
            stateone.IpEndPoint = (IPEndPoint)connectResult.Content.RemoteEndPoint;
            stateone.LoginAlias = ClientAlias;
            stateone.WorkSocket = connectResult.Content;
            stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead,
                                             stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None,
                                             new AsyncCallback(HeadBytesReceiveCallback), stateone);


            byte[] bytesTemp = new byte[16];
            BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(bytesTemp, 0);
            SendBytes(stateone, HslProtocol.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, Token, bytesTemp));


            stateone.HeartTime = DateTime.Now;
            IsClientStart      = true;
            LoginSuccess?.Invoke( );
            LogNet?.WriteDebug(ToString( ), "Login Server Success, Times: " + ConnectFailedCount);
            IsClientConnecting = false;
            Thread.Sleep(1000);
        }
Beispiel #21
0
 private void RaiseLoginFailed(WebTokenRequestStatus e)
 {
     Debug.WriteLine($"LoginFailed: {e}");
     LoginFailed?.Invoke(this, e);
 }
Beispiel #22
0
 private void LoginServices_LoginFailed() => LoginFailed?.Invoke();
        protected void ProcessMessage(byte[] raw_data_buffer)
        {
            if (mServerReactionStopwatch != null)
            {
                mServerReactionStopwatch.Stop();
                ServerReaction = mServerReactionStopwatch.Elapsed;
            }

            StopCheckConnection();

            var message = MessagePackDeserializer.Parse(raw_data_buffer) as SnipeObject;

            if (message != null)
            {
                string      message_type  = message.SafeGetString("t");
                string      error_code    = message.SafeGetString("errorCode");
                int         request_id    = message.SafeGetValue <int>("id");
                SnipeObject response_data = message.SafeGetValue <SnipeObject>("data");

                DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - {request_id} - {message_type} {error_code} {response_data?.ToJSONString()}");

                if (!mLoggedIn)
                {
                    if (message_type == SnipeMessageTypes.USER_LOGIN)
                    {
                        if (error_code == SnipeErrorCodes.OK)
                        {
                            DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - Login Succeeded");

                            mLoggedIn = true;

                            if (response_data != null)
                            {
                                this.ConnectionId = response_data.SafeGetString("connectionID");
                            }
                            else
                            {
                                this.ConnectionId = "";
                            }

                            try
                            {
                                LoginSucceeded?.Invoke();
                            }
                            catch (Exception e)
                            {
                                DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - LoginSucceeded invokation error: " + e.Message);
                            }

                            if (mHeartbeatEnabled)
                            {
                                StartHeartbeat();
                            }
                        }
                        else
                        {
                            DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - Login Failed");

                            try
                            {
                                LoginFailed?.Invoke(error_code);
                            }
                            catch (Exception e)
                            {
                                DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - LoginFailed invokation error: " + e.Message);
                            }
                        }
                    }
                }

                if (MessageReceived != null)
                {
                    try
                    {
                        MessageReceived.Invoke(message_type, error_code, response_data, request_id);
                    }
                    catch (Exception e)
                    {
                        DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - MessageReceived invokation error: " + e.Message + "\n" + e.StackTrace);
                    }
                }
                else
                {
                    DebugLogger.Log($"[SnipeClient] [{ConnectionId}] ProcessMessage - no MessageReceived listeners");
                }

                if (mHeartbeatEnabled)
                {
                    ResetHeartbeatTimer();
                }
            }
        }
Beispiel #24
0
 private void LoginFailedHandler()
 {
     LoginFailed?.Invoke(this, "Неправильный логин или пароль");
 }
Beispiel #25
0
        private Task Receiver(NetworkStream stream, CancellationTokenSource cts)
        {
            return(new Task(() =>
            {
                Trace.TraceInformation("Receiver task starting...");
                //stream.ReadTimeout = 5000;
                try
                {
                    while (true)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            break;
                        }
                        DataPackage dataPackage = DataPackage.FromStream(stream);
                        switch (dataPackage.Type)
                        {
                        case MessageType.SYSTEM_LOGIN_OK:
                            {
                                LoginInfo info = Serializer.Deserialize <LoginInfo>(dataPackage.Data);
                                Name = info.Name;
                                LoginOK?.Invoke(this, info);
                            }
                            break;

                        case MessageType.SYSTEM_LOGIN_FAILED:
                            {
                                LoginInfo info = Serializer.Deserialize <LoginInfo>(dataPackage.Data);
                                LoginFailed?.Invoke(this, info);
                            }
                            break;

                        case MessageType.SYSTEM_JOIN_ROOM_OK:
                            {
                                RoomInfo roomInfo = Serializer.Deserialize <RoomInfo>(dataPackage.Data);
                                JoinedInRoom?.Invoke(this, roomInfo);
                            }
                            break;

                        case MessageType.SYSTEM_LEAVE_ROOM_OK:
                            {
                                RoomInfo roomInfo = Serializer.Deserialize <RoomInfo>(dataPackage.Data);
                                LeavedFromRoom?.Invoke(this, roomInfo);
                            }
                            break;

                        case MessageType.CLIENT_MESSAGE:
                            {
                                Message message = Serializer.Deserialize <Message>(dataPackage.Data);
                                MessageReceived?.Invoke(this, message);
                            }
                            break;

                        case MessageType.CLIENT_IMAGE_MESSAGE:
                            {
                                var imageMessage = Serializer.Deserialize <ImageMessage>(dataPackage.Data);
                                ImageMessageReceived?.Invoke(this, imageMessage);
                            }
                            break;

                        case MessageType.CLIENT_FILE_MESSAGE:
                            {
                                var fileMessage = Serializer.Deserialize <FileMessage>(dataPackage.Data);
                                FileMessageReived?.Invoke(this, fileMessage);
                            }
                            break;

                        case MessageType.SYSTEM_FILE_TRANSFER:
                            {
                                var fileMessage = Serializer.Deserialize <FileMessage>(dataPackage.Data);
                                FileReived?.Invoke(this, fileMessage);
                            }
                            break;

                        case MessageType.SYSTEM_MESSAGE_OK:
                            {
                                Receipt receipt = Serializer.Deserialize <Receipt>(dataPackage.Data);
                                MessageArrivied?.Invoke(this, receipt);
                            }
                            break;

                        case MessageType.SYSTEM_MESSAGE:
                            {
                                var message = Encoding.UTF8.GetString(dataPackage.Data);
                                SystemMessageReceived?.Invoke(this, message);
                                break;
                            }

                        case MessageType.CLIENT_LOGOUT:
                            {
                                Name = null;
                                LogoutOK?.Invoke(this, null);
                                goto default;
                            }

                        default:
                            UnknownMessageReceived?.Invoke(this, new SystemMessageEventArgs(dataPackage.Type, dataPackage.Data));
                            break;
                        }
                    }
                }
                catch (EndOfStreamException ex)
                {
                    Debug.WriteLine($"Client {Name} Receiver: {ex.Message}");
                }
                catch (IOException ex)
                {
                    if (ex.InnerException is SocketException)
                    {
                        SocketExceptionRaising?.Invoke(this, (SocketException)ex.InnerException);
                    }
                    else
                    {
                        Trace.TraceInformation($"{ex}");
                    }
                }
                ReceiverTaskExited?.Invoke(this, null);
                Trace.TraceInformation("Receiver task exited");
            }, TaskCreationOptions.LongRunning));
        }
Beispiel #26
0
 private void Disconnect(IClient client)
 {
     LoginFailed?.Invoke(client);
     //
     State = LoginStates.Disconnected;
 }
Beispiel #27
0
 public void NotifyLoginFailed()
 {
     LoginFailed?.Invoke(this, EventArgs.Empty);
 }
Beispiel #28
0
 internal void OnLoginFailed(LoginFailType failType)
 {
     _api.Logger.Debug($"Login failed with type {failType}");
     LoginFailed?.Invoke(failType);
     Disconnnect();
 }
Beispiel #29
0
        private void ThreadLogin()
        {
            lock (lock_connecting)
            {
                if (Is_Client_Connecting)
                {
                    return;
                }
                Is_Client_Connecting = true;
            }


            if (Connect_Failed_Count == 0)
            {
                MessageAlerts?.Invoke("正在连接服务器...");
            }
            else
            {
                int count = 10;
                while (count > 0)
                {
                    if (IsQuie)
                    {
                        return;
                    }
                    MessageAlerts?.Invoke("连接断开,等待" + count-- + "秒后重新连接");
                    Thread.Sleep(1000);
                }
                MessageAlerts?.Invoke("正在尝试第" + Connect_Failed_Count + "次连接服务器...");
            }


            stateone.HeartTime = DateTime.Now;
            LogNet?.WriteDebug(LogHeaderText, "Begin Connect Server, Times: " + Connect_Failed_Count);


            OperateResult result = new OperateResult();

            if (!CreateSocketAndConnect(out Socket socket, EndPointServer, result))
            {
                Connect_Failed_Count++;
                Is_Client_Connecting = false;
                LoginFailed?.Invoke(Connect_Failed_Count);
                LogNet?.WriteDebug(LogHeaderText, "Connected Failed, Times: " + Connect_Failed_Count);
                // 连接失败,重新连接服务器
                ReconnectServer();
                return;
            }

            // 连接成功,发送数据信息
            if (!SendStringAndCheckReceive(
                    socket,
                    1,
                    ClientAlias,
                    result
                    ))
            {
                Connect_Failed_Count++;
                Is_Client_Connecting = false;
                LogNet?.WriteDebug(LogHeaderText, "Login Server Failed, Times: " + Connect_Failed_Count);
                LoginFailed?.Invoke(Connect_Failed_Count);
                // 连接失败,重新连接服务器
                ReconnectServer();
                return;
            }

            // 登录成功
            Connect_Failed_Count = 0;
            stateone.IpEndPoint  = (IPEndPoint)socket.RemoteEndPoint;
            stateone.LoginAlias  = ClientAlias;
            stateone.WorkSocket  = socket;
            stateone.WorkSocket.BeginReceive(stateone.BytesHead, stateone.AlreadyReceivedHead,
                                             stateone.BytesHead.Length - stateone.AlreadyReceivedHead, SocketFlags.None,
                                             new AsyncCallback(HeadReceiveCallback), stateone);

            // 发送一条验证消息
            // SendBytes(stateone, CommunicationCode.CommandBytes(CommunicationCode.Hsl_Protocol_Check_Secends));
            byte[] bytesTemp = new byte[16];
            BitConverter.GetBytes(DateTime.Now.Ticks).CopyTo(bytesTemp, 0);
            SendBytes(stateone, NetSupport.CommandBytes(HslProtocol.ProtocolCheckSecends, 0, KeyToken, bytesTemp));


            stateone.HeartTime = DateTime.Now;
            Is_Client_Start    = true;
            LoginSuccess?.Invoke();

            LogNet?.WriteDebug(LogHeaderText, "Login Server Success, Times: " + Connect_Failed_Count);

            Is_Client_Connecting = false;

            Thread.Sleep(1000);
        }
Beispiel #30
0
 protected virtual void OnLoginFailed()
 {
     LoginFailed?.Invoke(this);
 }