Advertisement
tolikpunkoff

TestGetMessageServer

Mar 12th, 2017
507
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 3.36 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7.  
  8.  
  9. //TestGetMessageServer
  10. //Original code https://professorweb.ru/my/csharp/web/level3/3_2.php
  11.  
  12. namespace TestGetMessageServer
  13. {
  14.     class Program
  15.     {
  16.         static void Main(string[] args)
  17.         {
  18.             // Устанавливаем для сокета локальную конечную точку
  19.             IPHostEntry ipHost = Dns.GetHostEntry("10.10.0.30");
  20.             IPAddress ipAddr = ipHost.AddressList[0];
  21.             IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
  22.  
  23.             // Создаем сокет Tcp/Ip
  24.             Socket sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  25.  
  26.             // Назначаем сокет локальной конечной точке и слушаем входящие сокеты
  27.             try
  28.             {
  29.                 sListener.Bind(ipEndPoint);
  30.                 sListener.Listen(10);
  31.  
  32.                 // Начинаем слушать соединения
  33.                 while (true)
  34.                 {
  35.                     Console.WriteLine("Ожидаем соединение через порт {0}", ipEndPoint.Port);
  36.                     Console.WriteLine("Локальный адрес {0}", ipEndPoint.Address);
  37.  
  38.                     // Программа приостанавливается, ожидая входящее соединение
  39.                     Socket handler = sListener.Accept();                    
  40.                     string data = null;
  41.  
  42.                     // Мы дождались клиента, пытающегося с нами соединиться
  43.  
  44.                     byte[] bytes = new byte[1024];                    
  45.                     //на самом деле тут надо делать нормальную проверку
  46.                     Console.WriteLine("Сообщение получено, ожидаем данные (5 с)");
  47.                     Thread.Sleep(5000);
  48.  
  49.                     int bytesRec = handler.Receive(bytes);                    
  50.  
  51.                     data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
  52.                                        
  53.                     // Показываем данные на консоли
  54.                     Console.Write("Полученный текст: " + data + "\n\n");
  55.  
  56.                     // Отправляем ответ клиенту
  57.                     /*string reply = "Спасибо за запрос в " + data.Length.ToString()
  58.                             + " символов";
  59.                     byte[] msg = Encoding.UTF8.GetBytes(reply);
  60.                     handler.Send(msg);*/
  61.  
  62.                     if (data.IndexOf("-TheEnd-") > -1)
  63.                     {
  64.                         Console.WriteLine("Сервер завершил соединение с клиентом.");
  65.                         break;
  66.                     }
  67.  
  68.                     handler.Shutdown(SocketShutdown.Both);
  69.                     handler.Close();
  70.                 }
  71.             }
  72.             catch (Exception ex)
  73.             {
  74.                 Console.WriteLine(ex.ToString());
  75.             }
  76.             finally
  77.             {
  78.                 Console.ReadLine();
  79.             }
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement