Program.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace CsAp
  9. {
  10. class Program
  11. {
  12. static void Main(string[] args)
  13. {
  14. try
  15. {
  16. SendMessageFromSocket(11000);
  17. }
  18. catch (Exception ex)
  19. {
  20. Console.WriteLine(ex.ToString());
  21. }
  22. finally
  23. {
  24. Console.ReadLine();
  25. }
  26. }
  27. static void SendMessageFromSocket(int port)
  28. {
  29. // Буфер для входящих данных
  30. byte[] bytes = new byte[1024];
  31. // Соединяемся с удаленным устройством
  32. // Устанавливаем удаленную точку для сокета
  33. IPHostEntry ipHost = Dns.GetHostEntry("localhost");
  34. IPAddress ipAddr = ipHost.AddressList[0];
  35. IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);
  36. Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  37. // Соединяем сокет с удаленной точкой
  38. sender.Connect(ipEndPoint);
  39. Console.Write("Введите сообщение: ");
  40. string message = Console.ReadLine();
  41. Console.WriteLine("Сокет соединяется с {0} ", sender.RemoteEndPoint.ToString());
  42. byte[] msg = Encoding.UTF8.GetBytes(message);
  43. // Отправляем данные через сокет
  44. int bytesSent = sender.Send(msg);
  45. // Получаем ответ от сервера
  46. int bytesRec = sender.Receive(bytes);
  47. Console.WriteLine("\nОтвет от сервера: {0}\n\n", Encoding.UTF8.GetString(bytes, 0, bytesRec));
  48. // Используем рекурсию для неоднократного вызова SendMessageFromSocket()
  49. if (message.IndexOf("<TheEnd>") == -1)
  50. SendMessageFromSocket(port);
  51. // Освобождаем сокет
  52. sender.Shutdown(SocketShutdown.Both);
  53. sender.Close();
  54. }
  55. public class SessionUser
  56. {
  57. public int id_user { get; set; }
  58. public string date_start { get; set; }
  59. }
  60. }
  61. }