create server & client

This commit is contained in:
Sharikov P.P.
2026-01-16 00:30:19 +07:00
parent 879485cb54
commit cc41ec4f55
8 changed files with 884 additions and 0 deletions

415
.gitignore vendored Normal file
View File

@@ -0,0 +1,415 @@
# ---> VisualStudio
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
# but not Directory.Build.rsp, as it configures directory-level build defaults
!Directory.Build.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
*.ncb
*.aps
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix

36
LINUX.sln Normal file
View File

@@ -0,0 +1,36 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36908.2
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "f-cln", "f-cln\f-cln.csproj", "{4B89C61E-29A4-451E-9AAC-E00862DC825A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "f-srv", "f-srv\f-srv.csproj", "{BBCBE3C7-E7EE-4A51-8829-5632E3B8FC20}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Элементы решения", "Элементы решения", "{754FC069-D67B-A9D7-50A1-8D1CA196D8F1}"
ProjectSection(SolutionItems) = preProject
README.md = README.md
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B89C61E-29A4-451E-9AAC-E00862DC825A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B89C61E-29A4-451E-9AAC-E00862DC825A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B89C61E-29A4-451E-9AAC-E00862DC825A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B89C61E-29A4-451E-9AAC-E00862DC825A}.Release|Any CPU.Build.0 = Release|Any CPU
{BBCBE3C7-E7EE-4A51-8829-5632E3B8FC20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BBCBE3C7-E7EE-4A51-8829-5632E3B8FC20}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BBCBE3C7-E7EE-4A51-8829-5632E3B8FC20}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BBCBE3C7-E7EE-4A51-8829-5632E3B8FC20}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B82D1C4A-A28B-480E-B7C1-43F29B2452E6}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,5 @@
# WWW
arseny web
try to work

179
f-cln/Program.cs Normal file
View File

@@ -0,0 +1,179 @@
using System;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace f_cln
{
class Program
{
static async Task<int> Main(string[] args)
{
// Создание команды с аргументами
Option<string> ipOption = new("address", new[] { "--ip", "-i" })
{
Description = "IP адрес сервера (по умолчанию: localhost)",
DefaultValueFactory = parseResult => "localhost"
};
Option<int> portOption = new("port", new[] { "--port", "-p" })
{
Description = "Порт сервера (по умолчанию: 1771)",
DefaultValueFactory = parseResult => 1771
};
Option<string?> messageOption = new("message", new[] { "--message", "-m" })
{
Description = "Сообщение для отправки (если не указано, работает в интерактивном режиме)",
Arity = ArgumentArity.ZeroOrOne
};
var rootCommand = new RootCommand("Клиент для отправки строк серверу и получения их в обратном порядке")
{
ipOption,
portOption,
messageOption
};
rootCommand.Parse("--version").Invoke();
ParseResult parseResult = rootCommand.Parse(args);
if (parseResult.Errors.Count == 0)
{
string ip = parseResult.GetValue(ipOption) ?? "localhost";
int port = parseResult.GetValue(portOption);
string? message = parseResult.GetValue(messageOption);
try
{
if (!string.IsNullOrEmpty(message))
{
// Режим однократной отправки
await SendMessage(ip, port, message);
}
else
{
// Интерактивный режим
await RunInteractive(ip, port);
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Ошибка: {ex.Message}");
return 2;
}
}
else
{
foreach (ParseError parseError in parseResult.Errors)
{
Console.Error.WriteLine(parseError.Message);
}
return 1;
}
}
static async Task SendMessage(string ip, int port, string message)
{
try
{
Console.WriteLine($"Подключение к {ip}:{port}...");
using var client = new TcpClient();
await client.ConnectAsync(ip, port);
Console.WriteLine("Подключено к серверу");
using var stream = client.GetStream();
// Отправка сообщения
var messageBytes = Encoding.UTF8.GetBytes(message + Environment.NewLine);
await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
Console.WriteLine($"Отправлено: {message}");
// Чтение ответа
var buffer = new byte[1024];
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
var response = Encoding.UTF8.GetString(buffer, 0, bytesRead).TrimEnd('\n', '\r');
Console.WriteLine($"Получено: {response}");
}
}
catch (SocketException ex)
{
Console.WriteLine($"Сетевая ошибка: {ex.Message}");
throw;
}
}
static async Task RunInteractive(string ip, int port)
{
try
{
Console.WriteLine($"Подключение к {ip}:{port}...");
using var client = new TcpClient();
await client.ConnectAsync(ip, port);
Console.WriteLine("Подключено к серверу");
Console.WriteLine("Введите текст для отправки (или 'exit' для выхода):");
using var stream = client.GetStream();
var buffer = new byte[1024];
while (true)
{
// Чтение ввода пользователя
Console.Write("> ");
var input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
continue;
if (input.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Завершение работы...");
break;
}
try
{
// Отправка сообщения
var messageBytes = Encoding.UTF8.GetBytes(input + Environment.NewLine);
await stream.WriteAsync(messageBytes, 0, messageBytes.Length);
// Чтение ответа
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
var response = Encoding.UTF8.GetString(buffer, 0, bytesRead).TrimEnd('\n', '\r');
Console.WriteLine($"Ответ: {response}");
}
else
{
Console.WriteLine("Сервер отключился");
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка при отправке/получении: {ex.Message}");
break;
}
}
}
catch (SocketException ex)
{
Console.WriteLine($"Ошибка подключения: {ex.Message}");
}
}
}
}

17
f-cln/f-cln.csproj Normal file
View File

@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>f_cln</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<VersionPrefix>1.1.12 </VersionPrefix>
<VersionSuffix>63</VersionSuffix>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.2" />
</ItemGroup>
</Project>

206
f-srv/Program.cs Normal file
View File

@@ -0,0 +1,206 @@
using System;
using System.CommandLine;
using System.CommandLine.Parsing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace f_srv
{
class Program
{
private static CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private static TcpListener? _listener;
static async Task<int> Main(string[] args)
{
// Создание команды с аргументами
Option<IPAddress> ipOption = new("address", new[] { "--ip", "-i" })
{
Description = "IP адрес для прослушивания (по умолчанию: все интерфейсы)",
DefaultValueFactory = parseResult => IPAddress.Any
};
Option<int> portOption = new("port", new[] { "--port", "-p" })
{
Description = "Порт для прослушивания (по умолчанию: 1771)",
DefaultValueFactory = parseResult => 1771
};
var rootCommand = new RootCommand("Сервер для получения строк и отправки их в обратном порядке")
{
ipOption,
portOption
};
{
rootCommand.Parse("-h").Invoke();
rootCommand.Parse("--version").Invoke();
}
ParseResult parseResult = rootCommand.Parse(args);
if (parseResult.Errors.Count == 0)
{
IPAddress? ip = parseResult.GetValue(ipOption);
int port = parseResult.GetValue(portOption);
if (ip == null)
{
Console.Error.WriteLine("Ошибка: IP адрес не указан или имеет неверный формат");
return 2;
}
// Запускаем сервер в отдельной задаче
var serverTask = Task.Run(() => StartServer(ip, port, _cancellationTokenSource.Token));
// Ожидаем нажатие клавиши
Console.WriteLine("Сервер запущен. Нажмите любую клавишу для остановки...");
Console.ReadKey();
// Отправляем сигнал отмены
_cancellationTokenSource.Cancel();
// Останавливаем listener
_listener?.Stop();
// Ждем завершения сервера
await serverTask;
Console.WriteLine("Сервер остановлен.");
return 0;
}
else
{
foreach (ParseError parseError in parseResult.Errors)
{
Console.Error.WriteLine(parseError.Message);
}
return 1;
}
}
static async Task StartServer(IPAddress ip, int port, CancellationToken cancellationToken)
{
try
{
Console.WriteLine($"Запуск сервера на {ip}:{port}");
// Создание TCP listener
_listener = new TcpListener(ip, port);
_listener.Start();
Console.WriteLine("Сервер запущен. Ожидание подключений...");
while (!cancellationToken.IsCancellationRequested)
{
try
{
// Ожидание подключения клиента с таймаутом для проверки отмены
var acceptTask = _listener.AcceptTcpClientAsync();
var completedTask = await Task.WhenAny(acceptTask, Task.Delay(1000, cancellationToken));
if (completedTask == acceptTask && !cancellationToken.IsCancellationRequested)
{
var client = await acceptTask;
// Обработка клиента в отдельной задаче
_ = Task.Run(async () => await HandleClient(client, cancellationToken));
}
}
catch (OperationCanceledException)
{
// Игнорируем отмену
}
catch (Exception ex)
{
if (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine($"Ошибка при принятии подключения: {ex.Message}");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка: {ex.Message}");
}
finally
{
_listener?.Stop();
}
}
static async Task HandleClient(TcpClient client, CancellationToken cancellationToken)
{
var clientEndPoint = client.Client.RemoteEndPoint;
Console.WriteLine($"Подключен клиент: {clientEndPoint}");
try
{
using (client)
using (var stream = client.GetStream())
{
var buffer = new byte[1024];
while (!cancellationToken.IsCancellationRequested)
{
try
{
// Чтение данных от клиента с таймаутом
var readTask = stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
var completedTask = await Task.WhenAny(readTask, Task.Delay(1000, cancellationToken));
if (completedTask != readTask)
{
// Таймаут - проверяем отмену и продолжаем цикл
continue;
}
var bytesRead = await readTask;
if (bytesRead == 0)
{
Console.WriteLine($"Клиент отключился: {clientEndPoint}");
break;
}
// Преобразование байтов в строку
var receivedString = Encoding.UTF8.GetString(buffer, 0, bytesRead);
// Удаление символов новой строки для чистого вывода
var cleanString = receivedString.TrimEnd('\n', '\r');
Console.WriteLine($"Получено от {clientEndPoint}: {cleanString}");
// Реверсирование строки
var reversedString = ReverseString(cleanString);
Console.WriteLine($"Отправка: {reversedString}");
// Отправка реверсированной строки обратно клиенту
var responseBytes = Encoding.UTF8.GetBytes(reversedString + Environment.NewLine);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length, cancellationToken);
}
catch (OperationCanceledException)
{
// Игнорируем отмену при чтении/записи
break;
}
}
}
}
catch (Exception ex) when (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine($"Ошибка при работе с клиентом {clientEndPoint}: {ex.Message}");
}
}
static string ReverseString(string s)
{
var charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
}

View File

@@ -0,0 +1,8 @@
{
"profiles": {
"f-srv": {
"commandName": "Project",
"commandLineArgs": "--port 3113"
}
}
}

18
f-srv/f-srv.csproj Normal file
View File

@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<RootNamespace>f_srv</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PlatformTarget>AnyCPU</PlatformTarget>
<Version>0.0.11 </Version>
<VersionPrefix>1.1.12 </VersionPrefix>
<VersionSuffix>22 </VersionSuffix>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.CommandLine" Version="2.0.2" />
</ItemGroup>
</Project>