khuseiN

Untitled

May 13th, 2024
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.47 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using Npgsql;
  6.  
  7. namespace server
  8. {
  9. class Program
  10. {
  11. static TcpListener listener = null;
  12. static string connectionString = "Host=localhost;Port=5432;Username=adm;Password=adm;Database=MyDb";
  13. static Dictionary<string, string> credentials; //данные пользователей
  14. //static Dictionary<string, TcpClient> clients = new Dictionary<string, TcpClient>(); //подключенные клиенты
  15. static Dictionary<string, TcpClient> authclients = new Dictionary<string, TcpClient>(); //аутентифицированные клиенты
  16.  
  17. static void Main(string[] args)
  18. {
  19. credentials = ReadCredentialsFromDatabase();
  20.  
  21. listener = new TcpListener(IPAddress.Any, 8000); //прослушивание адреса
  22. listener.Start();
  23. Console.WriteLine("Сервер запущен. Ожидание подключений...");
  24.  
  25. while (true)
  26. {
  27. TcpClient client = listener.AcceptTcpClient();
  28. Thread clientThread = new Thread(() => HandleClient(client));
  29. clientThread.Start();
  30. }
  31. }
  32.  
  33. static Dictionary<string, string> ReadCredentialsFromDatabase()
  34. {
  35. Dictionary<string, string> credentials = new Dictionary<string, string>();
  36.  
  37. using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
  38. {
  39. connection.Open();
  40. string sql = "SELECT username, password FROM users";
  41. using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
  42. {
  43. using (NpgsqlDataReader reader = command.ExecuteReader())
  44. {
  45. while (reader.Read())
  46. {
  47. string username = reader.GetString(0);
  48. string password = reader.GetString(1);
  49. Console.WriteLine($"Получены данные из базы данных: {username}, {password}");
  50. credentials[username] = password;
  51. }
  52. }
  53. }
  54. }
  55. return credentials;
  56. }
  57.  
  58. static void HandleClient(TcpClient client)
  59. {
  60. NetworkStream stream = client.GetStream();
  61. byte[] buffer = new byte[1024]; //буфер для чтения данных
  62. int bytesRead; //количесвто прочитанных байтов
  63.  
  64. bool isAuthenticated = false;
  65.  
  66. while (true)
  67. {
  68. bytesRead = 0;
  69. try
  70. {
  71. bytesRead = stream.Read(buffer, 0, buffer.Length);
  72. }
  73. catch //выход при ошибке
  74. {
  75. break;
  76. }
  77. if (bytesRead == 0) //выход, если клиент отключился
  78. {
  79. break;
  80. }
  81.  
  82. string message = Encoding.UTF8.GetString(buffer, 0, bytesRead); //преобразование полученных данных в стринг
  83.  
  84. if (message.StartsWith("REGISTER"))
  85. {
  86. string[] registerData = message.Split(' '); //REGISTER логин пароль
  87. if (registerData.Length == 3) // 0 1 2
  88. {
  89. string username = registerData[1];
  90. string password = registerData[2];
  91.  
  92. if (!credentials.ContainsKey(username))
  93. {
  94. RegisterUser(username, password);
  95. SendMessage(client, "REGISTER_SUCCESS");
  96. Console.WriteLine($"{username} успешно зарегистрирован");
  97. }
  98. else
  99. {
  100. SendMessage(client, $"Ошибка регистрации. Пользователь {username} уже существует");
  101. return;
  102. }
  103. }
  104. else
  105. {
  106. SendMessage(client, "Неверный формат запроса на регистрацию");
  107. }
  108. }
  109. else if (message.StartsWith("AUTH"))//else if (!isAuthenticated && message.StartsWith("AUTH"))
  110. {
  111. string[] authData = message.Split(' ');
  112. if (authData.Length == 3)
  113. {
  114. string username = authData[1];
  115. string password = authData[2];
  116. if (credentials.ContainsKey(username) && credentials[username] == password)
  117. {
  118. if (authclients.ContainsKey(username))
  119. {
  120. SendMessage(client, $"Ошибка аутентификации. Пользователь {username} уже подключен");
  121. Console.WriteLine($"{username} уже подключен");
  122. client.Close();
  123. return;
  124. }
  125. authclients[username] = client;
  126.  
  127. SendMessage(client, "AUTH_SUCCES");
  128. Console.WriteLine($"{username} успешно аутентифицирован");
  129. isAuthenticated = true;
  130. }
  131. else if(credentials.ContainsKey(username) && credentials[username] != password)
  132. {
  133. SendMessage(client, $"Ошибка аутентификации {username}");
  134. Console.WriteLine($"{username} ошибка аутентификации");
  135. client.Close();
  136. }
  137. else {
  138. SendMessage(client, $"Пользователь с логином {username} не существует");
  139. Console.WriteLine($"{username} пошел нахуй");
  140. client.Close();
  141. }
  142. }
  143. }
  144.  
  145. Console.WriteLine($"Получено сообщение от клиента {message}");
  146. foreach (var kvp in authclients) //перебор элементов
  147. {
  148. if (kvp.Value != client && kvp.Value.Connected)
  149. {
  150. if (!message.StartsWith("AUTH"))
  151. {
  152. SendMessage(kvp.Value, message);
  153. }
  154. }
  155. }
  156.  
  157. }
  158. Console.WriteLine("Клиент отключился");
  159. foreach (var kvp in authclients) //перебор элементов
  160. {
  161. if (kvp.Value == client)
  162. {
  163. authclients.Remove(kvp.Key);
  164. }
  165. }
  166. client.Close();
  167. }
  168.  
  169. static void RegisterUser(string username, string password)
  170. {
  171. using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
  172. {
  173. connection.Open();
  174.  
  175. string sql = "INSERT INTO users (username, password) VALUES (@username, @password)";
  176. using (NpgsqlCommand command = new NpgsqlCommand(sql, connection))
  177. {
  178. command.Parameters.AddWithValue("username", username);
  179. command.Parameters.AddWithValue("password", password);
  180. command.ExecuteNonQuery();
  181. }
  182. credentials[username] = password;
  183. }
  184. }
  185.  
  186. static void SendMessage(TcpClient client, string message)
  187. {
  188. NetworkStream stream = client.GetStream();
  189. byte[] buffer = Encoding.UTF8.GetBytes(message);
  190. stream.Write(buffer, 0, buffer.Length);
  191. }
  192. }
  193. }
Advertisement
Add Comment
Please, Sign In to add comment