/// <summary> /// This login uses a flat file system, data/users/{0}.user - the users name is the file. /// </summary> /// <param name="data"></param> /// <param name="client"></param> /// <returns></returns> public bool Login(byte[] data, Client client) { try { BinaryBuffer buff = new BinaryBuffer(data, true); client.Username = buff.ReadString(buff.ReadInt()); // Username client.Password = buff.ReadString(buff.ReadInt()); // Password buff.EndRead(); buff = new BinaryBuffer(File.ReadAllBytes(string.Format(@"data/users/{0}.svpref", client.Username)), true); LoadClientArguments(ref buff, ref client); // does pass equal? string arg; client.GetArgument("Password", out arg); if (arg != client.Password) return false; buff.EndRead(); } catch (Exception) { return false; } return true; }
/// <summary> /// This function will run not matter if it errors... /// </summary> /// <param name="data"></param> /// <param name="client"></param> public void LoadClientArguments(ref BinaryBuffer data, ref Client client) { //how many arguments do we have stored? try { int Total = data.ReadInt(); for (int i = 0; i < Total; i++) client.Arguments.Add(new ClientArgument(data.ReadString(data.ReadInt()), data.ReadByte(), data.ReadByteArray(data.ReadInt()))); } catch (Exception) { // If the file is out of order, they lose there data. // because if they can login then the file has been changed manually. } }
/// <summary> /// Used to join a new Client with a Closed Client. /// </summary> /// <param name="client"></param> public void JoinClient(Client client) { if (!ServerFirewall.ClientAllowed(new IpAddress(client.TcpConnection.Client.LocalEndPoint.ToString()))) return; bool Added = false; lock (ServerClients) { for (int i = ServerClients.Count - 1; i >= 0; i--) { if (ServerClients[i] == null || (ServerClients[i].TcpConnection == null || !ServerClients[i].TcpConnection.Connected)) { if (Added) { ServerClients.RemoveAt(i); } else { ServerClients[i] = client; Added = true; } } } client.SessionId = ServerMaxSessionId++; Console.WriteLine("Client {1}: {0} has connected...", client.TcpConnection.Client.LocalEndPoint.ToString(), client.SessionId); if(!Added) { ServerClients.Add(client); } } }
/// <summary> /// Wait for a new client to connect to the server. /// </summary> public async void WaitForConnections() { ServerRunning = true; ServerListener = new TcpListener(IPAddress.Any, ServerPort); ServerListener.Start(); Console.WriteLine("Listening on {0}...", ServerListener.LocalEndpoint.ToString()); Console.WriteLine("Waiting for connections..."); while(ServerRunning) { try { Client IncommingClient = new Client(await ServerListener.AcceptTcpClientAsync(), this); if (IncommingClient.TcpConnection.Connected) { JoinClient(IncommingClient); Task.Run(new Action(IncommingClient.Launch)); } } catch (Exception) { } } }