123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using System;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- namespace Lab20Client
- {
- class MainClass
- {
- public static void Main(string[] args)
- {
- //Console.OutputEncoding = Encoding.GetEncoding(866); ;
- try
- {
- Communicate("localhost", 8888);
- }
- catch (Exception exc)
- {
- Console.WriteLine(exc.ToString());
- }
- }
- private static void Communicate(string hostname, int port)
- {
- IPHostEntry iPHost = Dns.GetHostEntry(hostname);
- IPAddress iPAddress = iPHost.AddressList[0];
- IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, port);
- Socket socket = new Socket(
- iPAddress.AddressFamily,
- SocketType.Stream,
- ProtocolType.Tcp
- );
- socket.Connect(iPEndPoint);
- // Отправка сообщения
- Console.Write("Enter message: ");
- string message = Console.ReadLine();
- Console.WriteLine($"Connecting to port: {iPEndPoint}");
- byte[] data = Encoding.UTF8.GetBytes(message);
- int bytesSent = socket.Send(data);
- // Принятие ответа
- byte[] bytes = new byte[1024];
- int bytesRec = socket.Receive(bytes);
- Console.WriteLine($"Server responded: \"{Encoding.UTF8.GetString(bytes, 0, bytesRec)}\"");
- if (message.IndexOf("<TheEnd>") == -1)
- {
- Communicate(hostname, port);
- }
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- }
- }
- }
|