Advertisement
Guest User

Untitled

a guest
May 26th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.96 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Net;
  4. using System.Net.Sockets;
  5.  
  6. namespace SocketClient
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             try
  13.             {
  14.                 SendMessageFromSocket(11000);
  15.             }
  16.             catch (Exception ex)
  17.             {
  18.                 Console.WriteLine(ex.ToString());
  19.             }
  20.             finally
  21.             {
  22.                 Console.ReadLine();
  23.             }
  24.         }
  25.  
  26.         static void SendMessageFromSocket(int port)
  27.         {
  28.             // Буфер для входящих данных
  29.             byte[] bytes = new byte[1024];
  30.  
  31.             // Соединяемся с удаленным устройством
  32.  
  33.             // Устанавливаем удаленную точку для сокета
  34.             IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
  35.             IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);
  36.             Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  37.  
  38.             // Соединяем сокет с удаленной точкой
  39.             sender.Connect(ipEndPoint);
  40.  
  41.             Console.Write("Введите сообщение: ");
  42.             string message = Console.ReadLine();
  43.  
  44.             Console.WriteLine("Сокет соединяется с {0} ", sender.RemoteEndPoint.ToString());
  45.             byte[] msg = Encoding.UTF8.GetBytes(message);
  46.  
  47.             // Отправляем данные через сокет
  48.             int bytesSent = sender.Send(msg);
  49.  
  50.             // Получаем ответ от сервера
  51.             int bytesRec = sender.Receive(bytes);
  52.  
  53.             Console.WriteLine("Ответ от сервера: {0}", Encoding.UTF8.GetString(bytes, 0, bytesRec));
  54.  
  55.  
  56.             // Освобождаем сокет
  57.             sender.Shutdown(SocketShutdown.Both);
  58.             sender.Close();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement