Program.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Text;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace Lab20Server
  6. {
  7. class Program
  8. {
  9. public static void Main(string[] args)
  10. {
  11. //Console.OutputEncoding = Encoding.GetEncoding(866);
  12. Console.WriteLine("Server started");
  13. IPHostEntry iPHost = Dns.GetHostEntry("localhost");
  14. IPAddress iPAddress = iPHost.AddressList[0];
  15. IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);
  16. Socket socket = new Socket(
  17. iPAddress.AddressFamily,
  18. SocketType.Stream,
  19. ProtocolType.Tcp
  20. );
  21. try
  22. {
  23. socket.Bind(iPEndPoint);
  24. socket.Listen(10);
  25. while (true)
  26. {
  27. Console.WriteLine($"Listening on port {iPEndPoint}");
  28. // Принятие данных
  29. Socket s = socket.Accept();
  30. string data = null;
  31. byte[] bytes = new byte[1024];
  32. int bytesCount = s.Receive(bytes);
  33. data += Encoding.UTF8.GetString(bytes, 0, bytesCount);
  34. Console.WriteLine($"Data from client: {data}\n\n");
  35. // Эхо
  36. string reply = $"Query size: {data.Length} chars";
  37. byte[] msg = Encoding.UTF8.GetBytes(reply);
  38. s.Send(msg);
  39. // Проверка на закрытие
  40. if (data.IndexOf("<TheEnd>") > -1)
  41. {
  42. Console.WriteLine("Connection closed");
  43. break;
  44. }
  45. s.Shutdown(SocketShutdown.Both);
  46. s.Close();
  47. }
  48. }
  49. catch (Exception exc)
  50. {
  51. Console.WriteLine(exc.ToString());
  52. }
  53. }
  54. }
  55. }