Advertisement
khuseiN

AVSKS

May 7th, 2024
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.24 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading;
  6. using System.IO;
  7. using System.Collections.Generic;
  8.  
  9. namespace server
  10. {
  11.     class Program
  12.     {
  13.         static TcpListener listener = null;
  14.         static Dictionary<string, string> credentials;
  15.         static Dictionary<string, TcpClient> clients = new Dictionary<string, TcpClient>();
  16.         static Dictionary<string, TcpClient> authclients = new Dictionary<string, TcpClient>();
  17.  
  18.         static void Main(string[] args)
  19.         {
  20.             string filePath = "clients.txt";
  21.             credentials = ReadCredentialsFromFile(filePath);
  22.  
  23.             listener = new TcpListener(IPAddress.Any, 8000);
  24.             listener.Start();
  25.             Console.WriteLine("Сервер запущен. Ожидание подключений...");
  26.  
  27.             while (true)
  28.             {
  29.                 TcpClient client = listener.AcceptTcpClient();
  30.                 Thread clientThread = new Thread(() => HandleClient(client));
  31.                 clientThread.Start();
  32.             }
  33.         }
  34.  
  35.         static Dictionary<string, string> ReadCredentialsFromFile(string filePath)
  36.         {
  37.             Dictionary<string, string> credentials = new Dictionary<string, string>();
  38.             try
  39.             {
  40.                 string[] lines = File.ReadAllLines(filePath);
  41.                 foreach (string line in lines)
  42.                 {
  43.                     string[] tokens = line.Split(' ');
  44.                     if (tokens.Length == 2)
  45.                     {
  46.                         string username = tokens[0];
  47.                         string password = tokens[1];
  48.                         credentials[username] = password;
  49.                     }
  50.                 }
  51.             }
  52.             catch (Exception ex)
  53.             {
  54.                 Console.WriteLine($"Ошибка при чтении файла: {ex.Message}");
  55.             }
  56.             return credentials;
  57.         }
  58.  
  59.         static void HandleClient(TcpClient client)
  60.         {
  61.             NetworkStream stream = client.GetStream();
  62.             byte[] buffer = new byte[1024];
  63.             int bytesRead;
  64.  
  65.             bool isAuthenticated = false;
  66.  
  67.             while (true)
  68.             {
  69.                 bytesRead = 0;
  70.                 try
  71.                 {
  72.                     bytesRead = stream.Read(buffer, 0, buffer.Length);
  73.                 }
  74.                 catch
  75.                 {
  76.                     break;
  77.                 }
  78.                 if (bytesRead == 0)
  79.                 {
  80.                     break;
  81.                 }
  82.  
  83.                 string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
  84.  
  85.                 if (!isAuthenticated && message.StartsWith("AUTH"))
  86.                 {
  87.                     string[] authData = message.Split(' ');
  88.                     if (authData.Length == 3)
  89.                     {
  90.                         string username = authData[1];
  91.                         string password = authData[2];
  92.                         if (credentials.ContainsKey(username) && credentials[username] == password)
  93.                         {
  94.                             if (authclients.ContainsKey(username))
  95.                             {
  96.                                 SendMessage(client, "Ошибка: клиент с даннымм логином уже подключен");
  97.                                 Console.WriteLine($"{username} уже подключен");
  98.                                 client.Close();
  99.                             }
  100.                             else
  101.                             {
  102.                                 authclients[username] = client;
  103.                                 clients[username] = client;
  104.                                 SendMessage(client, "AUTH_SUCCES");
  105.                                 Console.WriteLine($"{username} успешно аутентифицирован");
  106.                                 isAuthenticated = true;
  107.                             }
  108.                         }
  109.                         else
  110.                         {
  111.                             SendMessage(client, $"Ошибка аутентификации {username}");
  112.                             Console.WriteLine($"{username} ошибка аутентификации");
  113.                             client.Close();
  114.                         }
  115.                     }
  116.                 }
  117.  
  118.                 Console.WriteLine($"Получено сообщение от клиента {message}");
  119.                 foreach (var kvp in authclients)
  120.                 {
  121.                     if (kvp.Value != client && kvp.Value.Connected)
  122.                     {
  123.                         if (!message.StartsWith("AUTH"))
  124.                         {
  125.                             SendMessage(kvp.Value, message);
  126.                         }
  127.                     }
  128.                 }
  129.             }
  130.             Console.WriteLine("Клиент отключился");
  131.             client.Close();
  132.         }
  133.  
  134.         static void SendMessage(TcpClient client, string message)
  135.         {
  136.             NetworkStream stream = client.GetStream();
  137.             byte[] buffer = Encoding.UTF8.GetBytes(message);
  138.             stream.Write(buffer, 0, buffer.Length);
  139.         }
  140.     }
  141. }
  142.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement