Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- namespace SocketClient
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- SendMessageFromSocket(11000);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.ToString());
- }
- finally
- {
- Console.ReadLine();
- }
- }
- static void SendMessageFromSocket(int port)
- {
- // Буфер для входящих данных
- byte[] bytes = new byte[1024];
- // Соединяемся с удаленным устройством
- // Устанавливаем удаленную точку для сокета
- IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
- IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);
- Socket sender = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- // Соединяем сокет с удаленной точкой
- sender.Connect(ipEndPoint);
- Console.Write("Введите сообщение: ");
- string message = Console.ReadLine();
- Console.WriteLine("Сокет соединяется с {0} ", sender.RemoteEndPoint.ToString());
- byte[] msg = Encoding.UTF8.GetBytes(message);
- // Отправляем данные через сокет
- int bytesSent = sender.Send(msg);
- // Получаем ответ от сервера
- int bytesRec = sender.Receive(bytes);
- Console.WriteLine("Ответ от сервера: {0}", Encoding.UTF8.GetString(bytes, 0, bytesRec));
- // Освобождаем сокет
- sender.Shutdown(SocketShutdown.Both);
- sender.Close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement