Program.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System;
  2. using System.Text;
  3. using System.Net;
  4. using System.Net.Sockets;
  5. namespace Lab20Client
  6. {
  7. class MainClass
  8. {
  9. public static void Main(string[] args)
  10. {
  11. //Console.OutputEncoding = Encoding.GetEncoding(866); ;
  12. try
  13. {
  14. Communicate("localhost", 8888);
  15. }
  16. catch (Exception exc)
  17. {
  18. Console.WriteLine(exc.ToString());
  19. }
  20. }
  21. private static void Communicate(string hostname, int port)
  22. {
  23. IPHostEntry iPHost = Dns.GetHostEntry(hostname);
  24. IPAddress iPAddress = iPHost.AddressList[0];
  25. IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
  26. Socket socket = new Socket(
  27. iPAddress.AddressFamily,
  28. SocketType.Stream,
  29. ProtocolType.Tcp
  30. );
  31. socket.Connect(iPEndPoint);
  32. // Отправка сообщения
  33. Console.Write("Enter message: ");
  34. string message = Console.ReadLine();
  35. Console.WriteLine($"Connecting to port: {iPEndPoint}");
  36. byte[] data = Encoding.UTF8.GetBytes(message);
  37. int bytesSent = socket.Send(data);
  38. // Принятие ответа
  39. byte[] bytes = new byte[1024];
  40. int bytesRec = socket.Receive(bytes);
  41. Console.WriteLine($"Server responded: \"{Encoding.UTF8.GetString(bytes, 0, bytesRec)}\"");
  42. if (message.IndexOf("<TheEnd>") == -1)
  43. {
  44. Communicate(hostname, port);
  45. }
  46. socket.Shutdown(SocketShutdown.Both);
  47. socket.Close();
  48. }
  49. }
  50. }