/// <summary> /// Runs when lobby succes /// </summary> /// <param name="reason"></param> void NetLobby_OnSucces(string reason) { _connection = new Connection(_client, _client.ServerConnection, (_client.ServerConnection.Tag as Handshake).CreateEncryption()); try { OnAuthenticated.Invoke(_connection); SetStep(AuthenticationStatus.Authenticated); } catch (InvalidOperationException) { OnAuthenticationFailed.Invoke("Error occured while creation Connection"); SetStep(AuthenticationStatus.HandshakeFailed); } }
/// <summary> /// /// </summary> public void Loop() { try { // This is checked each cycle while (this.IsRunning) { _client.MessageReceivedEvent.WaitOne(1000); NetIncomingMessage msg = _client.ReadMessage(); // No message received, please relieve CPU if (msg == null) { continue; } switch (msg.MessageType) { case NetIncomingMessageType.Data: if (msg.SenderConnection.Tag is Connection) { ((Connection)msg.SenderConnection.Tag).IncomingMessage(msg); } else { NetLobby.IncomingMessage(msg); } break; case NetIncomingMessageType.StatusChanged: NetConnectionStatus statusByte = (NetConnectionStatus)msg.ReadByte(); switch (statusByte) { case NetConnectionStatus.Disconnecting: break; // When disconnect is called and processed case NetConnectionStatus.Disconnected: // If already connection established, destroy resources if (msg.SenderConnection.Tag is Connection && !((Connection)msg.SenderConnection.Tag).IsDisposed) { ((Connection)msg.SenderConnection.Tag).Dispose(); } // Received a reason for disconnecting? (e.a. Handshake Fail) String finalReason = Encoding.UTF8.GetString(msg.ReadBytes((Int32)msg.ReadVariableUInt32())); // Some exceptions that should be catched but even so if (finalReason.StartsWith("Handshake data validation failed")) { SetStep(AuthenticationStatus.NoServerConnection); OnAuthenticationFailed.Invoke("Could not connect"); } else if (finalReason.StartsWith("Failed to establish")) { SetStep(AuthenticationStatus.NoServerConnection); OnAuthenticationTimeout.Invoke("Could not connect"); } Disconnect(""); break; case NetConnectionStatus.Connected: SetStep(AuthenticationStatus.ServerConnection); var username = _username; var password = _password; // Connected so lets start authenticating Authenticate(_client.ServerConnection, _username, _password); break; } break; } } Disconnect(""); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
/// <summary> /// Runs when handshake error occrus /// </summary> /// <param name="reason"></param> void NetLobby_OnError(string reason) { OnAuthenticationFailed.Invoke(reason); Disconnect("Error during handshake: " + reason); }
/// <summary> /// Method to raise authentication failed event. /// </summary> protected void RaiseAuthenticationFailed <T>(Client server, T response = null) where T : class { OnAuthenticationFailed?.Invoke(this, new ClientHttpEventArgs <T>(server, response)); }