public void SetLoggingIn()
 {
     StateConnection &= ~FlagsStateConnection.Disconnected;
     StateConnection &= ~FlagsStateConnection.Disconnecting;
     //StateConnection &= ~FlagsStateConnection.Connected;
     //StateConnection &= FlagsStateConnection.Connecting;
     StateConnection &= ~FlagsStateConnection.LoggedIn;
     StateConnection |= FlagsStateConnection.LoggingIn;
 }
        public bool ConnectTray(Socket ConnectingClientSocket, bool IsClientMode)
        {
            lock (this)
            {
                if (this == Clients.NoClient)
                {
                    return(false);
                }
                YSFClient.Socket = ConnectingClientSocket;
                #region Sneak the username in so we can name the receiver thread!
                Packets.Packet_01_Login LoginPacket = new Packets.Packet_01_Login("nameless", 20110207);
                try
                {
                    byte[] Size = new byte[4];
                    YSFClient.Socket.Receive(Size, 4, SocketFlags.Peek);
                    byte[] Full = new byte[BitConverter.ToUInt32(Size, 0) + 4];
                    YSFClient.Socket.Receive(Full, Full.Length, SocketFlags.Peek);
                    if (Full.Length > 28)
                    {
                        Username = Full.ToDataString().Substring(28).Split('\0')[0];
                    }
                    else
                    {
                        Username = Full.Skip(8).Take(16).ToArray().ToDataString().Split('\0')[0];
                    }
                    Version     = BitConverter.ToUInt32(Full, 24);
                    LoginPacket = new Packets.Packet_01_Login(Username, Version);
                    Packets.Packet_29_VersionNotify VersionPacket = new Packets.Packet_29_VersionNotify(Version);
                    //YSFClient.SendPacketNow(VersionPacket);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                #endregion
                #region OYS Tray Mode - Select Server!
                //string ServerListFile = System.Environment.ExpandEnvironmentVariables("%USERPROFILE%/Documents/YSFLIGHT.COM/YSFLIGHT/config/serverhistory.txt");
                //if (!Files.FileExists(ServerListFile))
                //{
                //    SendMessage("Could not load ServerHistory.txt from YSFlight settings folder.");
                //    Disconnect("No Host Server");
                //    return false;
                //}
                //string[] ServersList = Files.FileReadAllLines(ServerListFile);
                //List<ServerAddress> Processed = new List<ServerAddress>();
                //foreach (string ThisLine in ServersList)
                //{
                //    if (ThisLine.CountOccurances("(") < 1) continue;
                //    string Address = ThisLine.Split('(')[0];
                //    int Port = 0;
                //    bool Failed = !Int32.TryParse(ThisLine.Split('(')[1].Split(')')[0], out Port);
                //    if (!Failed) Processed.Add(new ServerAddress(Address, Port));
                //}
                ////Now show the server list!
                //SendMessage("Welcome to OpenYS-Tray! Please select your desired server:");
                //SendMessage("==========================================================");
                //int Offset = 0;
                //IPAddress TargetAddress = IPAddress.Parse("127.0.0.1");
                //int TargetPort = 7915;
                //while (true)
                //{
                //    ListServers:
                //    for (int i = 0; (i + Offset) < Processed.Count & i < 9; i++)
                //    {
                //        SendMessage("[" + i.ToString() +"] " + Processed[i + Offset].Address.Resize(64).Split('\0')[0] + ":" + Processed[i + Offset].Port.ToString());
                //    }
                //    SendMessage("[M] More Servers");
                //    SendMessage("[X] Quit");

                //    int Number = -1;
                //    while (true)
                //    {
                //        Packets.GenericPacket InPacket = YSFClient.ReceivePacket();
                //        if (InPacket.Type == 32)
                //        {
                //            Packets.Packet_32_ChatMessage ChatMessage = new Packets.Packet_32_ChatMessage(InPacket, Username);
                //            bool Failed = !Int32.TryParse(ChatMessage.Message.Substring(0,1), out Number);
                //            if (Failed)
                //            {
                //                char Upper = ChatMessage.Message.ToUpperInvariant()[0];
                //                if (Upper == 'M')
                //                {
                //                    Offset += 10;
                //                    if (Offset >= Processed.Count) Offset = 0;
                //                    SendMessage("Please select your desired server:");
                //                    SendMessage("==================================");
                //                    goto ListServers;
                //                }
                //                if (Upper == 'X')
                //                {
                //                    Disconnect("Quit");
                //                    return false;
                //                }
                //            }
                //            else
                //            {
                //                TargetAddress = Dns.GetHostAddresses(Processed[Offset + Number].Address)[0];
                //                TargetPort = Processed[Offset + Number].Port;
                //                break;
                //            }
                //        }
                //    }

                //    SendMessage("You Chose: " + Processed[Offset + Number].Address + ":" + Processed[Offset + Number].Port);
                //    SendMessage("    ");
                //    SendMessage("Logging in now...");
                //    SendMessage("=================");

                //    try
                //    {
                //        YSFServer.Socket.Connect(new IPEndPoint(TargetAddress, TargetPort));
                //    }
                //    catch (Exception e)
                //    {
                //        Log.Error(e);
                //        Console.WriteLine(ConsoleColor.Yellow, "Connecting client \"" + Username + "\" was unable to reach the host YSF Server - is it down?");
                //        SendMessage("Unable to reach the host YSF Server - is it down?");
                //        Disconnect("No Host Socket to connect to. (Failed to redirect client to host)");
                //        return false;
                //    }
                //    //Set the Server Packet Handler Here.
                //    YSFServer.Connect(YSFServer.Socket);
                //    //YSFServer.SendPacket(LoginPacket);
                //    break;
                //}

                #endregion
                #region OYS Server Mode - Start Receiver
                YSFClient.ConnectionContext = ClientIO.ConnectionContexts.Client;
                #endregion
                #region OYS Client Mode - Start Receiver
                if (IsClientMode)
                {
                    YSFServer.ConnectionContext = ClientIO.ConnectionContexts.Server;
                }
                #endregion
                StateConnection = Client.FlagsStateConnection.Connecting;
                return(true);
            }
        }
 public void ResetConnectionState()
 {
     StateConnection = FlagsStateConnection.Disconnected; //Not sure? Must be disconnected.
 }
        public bool Disconnect(string Reason)
        {
            lock (this)
            {
                if (IsDisconnecting())
                {
                    return(false);
                }
                if (IsDisconnected())
                {
                    return(false);
                }

                //Console.WriteLine(ConsoleColor.Red, Utilities.GetSourceCodePosition(1));
                if (IsFakeClient())
                {
                    return(true);
                }
                if (IsDisconnecting())
                {
                    Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnecting Flag is Currently ON, A duplicate has occured and will be ignored.");
                    return(false);
                }
                if (IsDisconnected())
                {
                    Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnect Flag is Currently ON, A duplicate has occured and will be ignored.");
                    return(false);
                }
                try
                {
                    if (YSFClient.Socket.Connected ||
                        (!YSFClient.Socket.Poll(1000, SelectMode.SelectRead) && YSFClient.Socket.Available != 0))
                    {
                        //The socket still exists!
                        //DO NOT DISCONNECT!

                        Log.Warning("Client " + Username + " Socket told to disconnect when it should not be disconnected? (Data Still Available?)");
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                }
                Log.Warning("Disconnect() Called for Client: " + Username + ". Disconnect Flag is Currently OFF, Setting to ON. (This is completely normal...)");
                Log.Warning("Disconnect() Reason: " + Reason);
                SetDisconnecting();
                #region Despawn Vehicle
                if (Vehicle != Vehicles.NoVehicle)
                {
                    //Need to tell all the other clients the vehicle is removed!
                    Packets.Packet_13_RemoveAirplane  RemoveAirplane   = new Packets.Packet_13_RemoveAirplane(Vehicle.ID);
                    Packets.Packet_06_Acknowledgement AcknowledgeLeave = new Packets.Packet_06_Acknowledgement(2, RemoveAirplane.ID);
                    foreach (Client OtherClient in Clients.AllClients.Exclude(this))
                    {
                        OtherClient.SendPacket(RemoveAirplane);
                        //OtherClient.GetPacket(AcknowledgeLeave);
                    }
                    if (Vehicle.VirtualCarrierObject_ID != 0)
                    {
                        Packets.Packet_19_RemoveGround RemoveVCO = new Packets.Packet_19_RemoveGround(Vehicle.VirtualCarrierObject_ID);
                        Clients.AllClients.Exclude(this).SendPacket(RemoveVCO);
                    }
                    Vehicles.List.RemoveAll(x => x == Vehicle);
                }
                #endregion
                Clients.RemoveClient(this); //remove self from the client list.
                #region Inform Players
                if ((this.Username == "nameless" & !this.ClientType.HasFlag(Client.FlagsClientType.YSFlightClient)) | this.IsBot())
                {
                    if (this.Username == "nameless")
                    {
                        if (Settings.Loading.BotPingMessages)
                        {
                            Console.WriteLine(ConsoleColor.Magenta, "Server was pinged by an unknown service.");
                        }
                    }
                    else if (this.IsBot())
                    {
                        if (Settings.Loading.BotPingMessages)
                        {
                            Console.WriteLine(ConsoleColor.Magenta, "Server was pinged by a serverlist.");
                        }
                    }
                }
                else
                {
                    foreach (Client OtherClient in Clients.AllClients.Exclude(this).ToArray())
                    {
                        OtherClient.SendMessage("&c" + Username + " left the server.");
                    }
                }
                #endregion
                #region Kill Client.
                try
                {
                    //lock (YSFClient.PacketWaiters)
                    //{
                    //    foreach (Connection.PacketWaiter ThisPacketWaiter in YSFClient.PacketWaiters.ToArray())
                    //    {
                    //        //force all listener threads to invalidate and cancel.
                    //        ThisPacketWaiter.Signal.Set();
                    //        ThisPacketWaiter.Signal.Dispose();
                    //    }
                    //}

                    //YSFClient.Disconnect();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                #endregion
                #region Kill Server.
                try
                {
                    //YSFServer.ReceiveThread.Abort();
                    //foreach (Connection.PacketWaiter ThisPacketWaiter in YSFServer.PacketWaiters.ToArray())
                    //{
                    //    //force all listener threads to invalidate and cancel.
                    //    ThisPacketWaiter.Signal.Set();
                    //    ThisPacketWaiter.Signal.Dispose();
                    //}

                    //YSFServer.Disconnect();
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                #endregion
                //YSFClient.PacketLog.Log();
                StateConnection = Client.FlagsStateConnection.Disconnected;
                return(true);
            }
        }