Last active
April 14, 2025 12:35
-
-
Save sunmeat/a104085a559f7b3f4cd5ff9f7dadb283 to your computer and use it in GitHub Desktop.
CLIENT SIDE network programming example 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
class Client | |
{ | |
private const int DEFAULT_BUFLEN = 512; | |
private const string DEFAULT_PORT = "27015"; | |
static void Main() | |
{ | |
Console.OutputEncoding = Encoding.UTF8; // кириллица | |
Console.Title = "CLIENT SIDE"; | |
try | |
{ | |
var ipAddress = IPAddress.Loopback; // IP-адрес локального хоста (127.0.0.1), который используется для подключения к серверу на текущем устройстве | |
var remoteEndPoint = new IPEndPoint(ipAddress, int.Parse(DEFAULT_PORT)); | |
var clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
clientSocket.Connect(remoteEndPoint); // инициирует подключение клиента к серверу по указанному конечному пункту (IP-адрес и порт) | |
Console.WriteLine("Подключение к серверу установлено."); | |
var message = "Привет от клиента!"; | |
byte[] messageBytes = Encoding.UTF8.GetBytes(message); | |
clientSocket.Send(messageBytes); | |
Console.WriteLine($"Сообщение отправлено: {message}"); | |
var buffer = new byte[DEFAULT_BUFLEN]; | |
int bytesReceived = clientSocket.Receive(buffer); | |
string response = Encoding.UTF8.GetString(buffer, 0, bytesReceived); | |
Console.WriteLine($"Ответ от сервера: {response}"); | |
clientSocket.Shutdown(SocketShutdown.Send); | |
clientSocket.Close(); | |
Console.WriteLine("Соединение с сервером закрыто."); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine($"Произошла ошибка: {ex.Message}"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
SERVER SIDE: https://gist.github.com/sunmeat/fdf1bcb10ffc34fd1a312075ad587e02