Skip to content

Instantly share code, notes, and snippets.

@evost
Created April 12, 2018 08:31
Show Gist options
  • Save evost/3cda8e2b811537e266285bdd55bf020f to your computer and use it in GitHub Desktop.
Save evost/3cda8e2b811537e266285bdd55bf020f to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCP_Client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите ip адрес");
string addr = Console.ReadLine();
Console.WriteLine("Введите номер порта?");
int port = int.Parse(Console.ReadLine());
Console.WriteLine("Нажмите любую кнопку для передачи данных");
Console.ReadKey();
//Создаем сокет
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//вводим необходимые параметры для сокета
IPAddress ip = IPAddress.Parse(addr);
IPEndPoint ipe = new IPEndPoint(ip, port);
//соединяемся с удаленным сокетом
s.Connect(ipe);
byte[] buffer = Encoding.ASCII.GetBytes("test");
byte[] temp = new byte[256];
int len = 0;
//передаем данные
s.Send(buffer, buffer.Length, 0);
//приняли
len = s.Receive(temp, temp.Length, 0);
Console.WriteLine(Encoding.ASCII.GetString(temp, 0, len));
//закрываем сокет
s.Close();
Console.WriteLine("Передача данных закончена");
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCP_Serv
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Введите номер порта?");
int port = int.Parse(Console.ReadLine());
//Создаем локальный сокет
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//вводим необходимые параметры для сокета
IPAddress ip = IPAddress.Any;
IPEndPoint ipe = new IPEndPoint(ip, port);
//объеденяем сокет с параметрами
s.Bind(ipe);
//устанавливаем порт в режим ожидания
s.Listen(100);
Console.WriteLine("Порт открыт, ожидаем соединения");
//создаем "удаленный" сокет
Socket c = s.Accept();
Console.WriteLine("Соединение установлено, начинаем прием данных");
byte[] buffer = new byte[256];
int len = 0;
//прием данных
len = c.Receive(buffer, 4, 0);
string data = Encoding.ASCII.GetString(buffer, 0, len);
Console.WriteLine(data);
Console.WriteLine("Прием данных закончен");
buffer = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
c.Send(buffer, DateTime.Now.ToString().Length, 0);
//закрываем сокет
c.Close();
s.Close();
//Console.WriteLine(Encoding.ASCII.GetString(buffer));
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment