12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using System;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- namespace Lab20Server
- {
- class Program
- {
- public static void Main(string[] args)
- {
- //Console.OutputEncoding = Encoding.GetEncoding(866);
- Console.WriteLine("Server started");
- IPHostEntry iPHost = Dns.GetHostEntry("localhost");
- IPAddress iPAddress = iPHost.AddressList[0];
- IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8888);
- Socket socket = new Socket(
- iPAddress.AddressFamily,
- SocketType.Stream,
- ProtocolType.Tcp
- );
- try
- {
- socket.Bind(iPEndPoint);
- socket.Listen(10);
- while (true)
- {
- Console.WriteLine($"Listening on port {iPEndPoint}");
- // Принятие данных
- Socket s = socket.Accept();
- string data = null;
- byte[] bytes = new byte[1024];
- int bytesCount = s.Receive(bytes);
- data += Encoding.UTF8.GetString(bytes, 0, bytesCount);
- Console.WriteLine($"Data from client: {data}\n\n");
- // Эхо
- string reply = $"Query size: {data.Length} chars";
- byte[] msg = Encoding.UTF8.GetBytes(reply);
- s.Send(msg);
- // Проверка на закрытие
- if (data.IndexOf("<TheEnd>") > -1)
- {
- Console.WriteLine("Connection closed");
- break;
- }
- s.Shutdown(SocketShutdown.Both);
- s.Close();
- }
- }
- catch (Exception exc)
- {
- Console.WriteLine(exc.ToString());
- }
- }
- }
- }
|