Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.47 KB | None | 0 0
  1. using System;
  2. using System.Net.Sockets;
  3. using System.Net;
  4. using System.Text;
  5.  
  6. public class SocketServer
  7. {
  8.     public static void Main(string [] args)
  9.     {
  10.         // устанавливаем для сокета локальную конечную точку
  11.         IPHostEntry ipHost = Dns.Resolve("localhost");
  12.         IPAddress ipAddr = ipHost.AddressList[0];
  13.         IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
  14.  
  15.         // создаем сокет TCP/IP
  16.         Socket sListener = new Socket(AddressFamily.InterNetwork,
  17.                                     SocketType.Stream, ProtocolType.Tcp);
  18.        
  19.         // назначаем сокет локальной конечной точке и
  20.         // слушаем входящие сокеты
  21.         try
  22.         {
  23.             sListener.Bind(ipEndPoint);
  24.             sListener.Listen(10);
  25.  
  26.             // Начинаем слушать соединение
  27.  
  28.             while (true)
  29.             {
  30.                 Console.WriteLine ("Waiting for a connection on port 0",
  31.                                     ipEndPoint);
  32.                
  33.                 // программа приостанавливается, ожидая входящее соединение
  34.                 Socket handler = sListener.Accept();
  35.  
  36.                 string data = null;
  37.  
  38.                 // мы дождались клиента, пытающегося с нами соединиться
  39.                 while (true)
  40.                 {
  41.                     byte[] bytes = new byte[1024];
  42.  
  43.                     int bytesRec = handler.Receive(bytes);
  44.  
  45.                     data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
  46.  
  47.                     if (data.IndexOf("<TheEnd>") > -1)
  48.                     {
  49.                         break;
  50.                     }
  51.                 }
  52.  
  53.                 // показываем данные на консоли
  54.                 Console.WriteLine("Text Received:  0", data);
  55.  
  56.                 string theReply = "Thank you for those "
  57.                                 + data.Length.ToString() + " characters. . .";
  58.  
  59.                 byte[] msg = Encoding.ASCII.GetBytes(theReply);
  60.  
  61.                 handler.Send(msg);
  62.                 handler.Shutdown(SocketShutdown.Both);
  63.                 handler.Close;
  64.             }
  65.         }
  66.         catch (Exception e)
  67.         {
  68.             Console.WriteLine(e.ToString());
  69.         }
  70.  
  71.     } //конец программы Main
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement