-
Notifications
You must be signed in to change notification settings - Fork 0
Test 2 #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Test 2 #7
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| | ||
| Microsoft Visual Studio Solution File, Format Version 12.00 | ||
| # Visual Studio Version 17 | ||
| VisualStudioVersion = 17.2.32505.173 | ||
| MinimumVisualStudioVersion = 10.0.40219.1 | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test2", "Test2\Test2.csproj", "{9C443126-FE1B-4B5D-9622-95C543247946}" | ||
| EndProject | ||
| Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test2Tests", "Test2Tests\Test2Tests.csproj", "{95155417-93B4-470F-99AE-4B89430F2E53}" | ||
| EndProject | ||
| Global | ||
| GlobalSection(SolutionConfigurationPlatforms) = preSolution | ||
| Debug|Any CPU = Debug|Any CPU | ||
| Release|Any CPU = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(ProjectConfigurationPlatforms) = postSolution | ||
| {9C443126-FE1B-4B5D-9622-95C543247946}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {9C443126-FE1B-4B5D-9622-95C543247946}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {9C443126-FE1B-4B5D-9622-95C543247946}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {9C443126-FE1B-4B5D-9622-95C543247946}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| {95155417-93B4-470F-99AE-4B89430F2E53}.Debug|Any CPU.ActiveCfg = Debug|Any CPU | ||
| {95155417-93B4-470F-99AE-4B89430F2E53}.Debug|Any CPU.Build.0 = Debug|Any CPU | ||
| {95155417-93B4-470F-99AE-4B89430F2E53}.Release|Any CPU.ActiveCfg = Release|Any CPU | ||
| {95155417-93B4-470F-99AE-4B89430F2E53}.Release|Any CPU.Build.0 = Release|Any CPU | ||
| EndGlobalSection | ||
| GlobalSection(SolutionProperties) = preSolution | ||
| HideSolutionNode = FALSE | ||
| EndGlobalSection | ||
| GlobalSection(ExtensibilityGlobals) = postSolution | ||
| SolutionGuid = {CF03D00E-ED5D-4B68-949C-102697743BA1} | ||
| EndGlobalSection | ||
| EndGlobal |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,86 @@ | ||||||
| namespace Server; | ||||||
|
|
||||||
| using System.Net.Sockets; | ||||||
| using System.Net; | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Сlass representing the client | ||||||
| /// </summary> | ||||||
| public class Client | ||||||
| { | ||||||
| private readonly int port; | ||||||
| private readonly IPAddress address; | ||||||
|
|
||||||
| private readonly CancellationTokenSource source = new(); | ||||||
|
|
||||||
| public CancellationTokenSource GetSource => source; | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Сonstructor | ||||||
| /// </summary> | ||||||
| /// <param name="adress">ip adress</param> | ||||||
| /// <param name="port">port</param> | ||||||
| public Client(IPAddress adress, int port) | ||||||
| { | ||||||
| this.port = port; | ||||||
| this.address = adress; | ||||||
| } | ||||||
|
|
||||||
| // Принять сообщение | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Для private-функции XML Documentation тоже вполне можно писать. Обычные комментарии используются для комментирования внутри тел методов в основном. |
||||||
| private async Task GetMessage(NetworkStream stream) { | ||||||
| using var streamReader = new StreamReader(stream); | ||||||
| var data = (await streamReader.ReadLineAsync()); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| while (data != "exit") { | ||||||
| Console.WriteLine($"{data}"); | ||||||
| data = (await streamReader.ReadLineAsync()); | ||||||
|
|
||||||
| if (source.IsCancellationRequested) | ||||||
| { | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| source.Cancel(); | ||||||
| } | ||||||
|
|
||||||
| // Отправить сообщение | ||||||
| private async Task SendMessage(NetworkStream stream) | ||||||
| { | ||||||
| using var streamWriter = new StreamWriter(stream) { AutoFlush = true}; | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| var data = Console.ReadLine(); | ||||||
| while (data != "exit") | ||||||
| { | ||||||
| await streamWriter.WriteLineAsync($"{data}"); | ||||||
|
|
||||||
| if (source.IsCancellationRequested) | ||||||
| { | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| source.Cancel(); | ||||||
| } | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Запуск клиентской части | ||||||
| /// </summary> | ||||||
| public async void Start() { | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. async void тут не по делу, это вообще конструкция для поддержки обработчиков событий в оконных библиотеках прежде всего |
||||||
| var client = new TcpClient(); | ||||||
| // Подключаемся к узлу | ||||||
| await client.ConnectAsync(address, port); | ||||||
|
|
||||||
| while (!source.Token.IsCancellationRequested) | ||||||
| { | ||||||
| // Получаем поток для записи и чтения | ||||||
| using var stream = client.GetStream(); | ||||||
| Task a = Task.Run(() => SendMessage(stream)); | ||||||
| Task b = Task.Run(() => GetMessage(stream)); | ||||||
| if (source.IsCancellationRequested) | ||||||
| { | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут ни одного блокирующего вызова нет — цикл, производящий миллионы задач просто |
||||||
|
|
||||||
| client.Close(); | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| using System.Net; | ||
|
|
||
| if (args.Length > 2 || args.Length <= 0) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!int.TryParse(args[0], out int port)) | ||
| { | ||
| Console.WriteLine("incorrect port input"); | ||
| return; | ||
| } | ||
|
|
||
| if (port < 1024 || port > 65535) | ||
| { | ||
| Console.WriteLine("incorrect port input"); | ||
| return; | ||
| } | ||
|
|
||
| if (args.Length == 1) { | ||
| var server = new Server.Server(port); | ||
| await Task.Run(() => server.Start()); | ||
| } | ||
| else { | ||
|
|
||
| if (!IPAddress.TryParse(args[1], out IPAddress? ip)) | ||
| { | ||
| Console.WriteLine("incorrect ip address input"); | ||
| return; | ||
| } | ||
|
|
||
| var client = new Server.Client(ip!, port); | ||
| await Task.Run(() => client.Start()); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Вот тут вышел прострел ноги — client.Start возвращает void, ждать Task.Run не на чем, и она тут же возвращает управление. Клиент закрывается, даже не успев установить соединение. Но, честно говоря, я вообще без идей, зачем вместо |
||
| } | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,89 @@ | ||||||
| namespace Server; | ||||||
|
|
||||||
| using System.Net.Sockets; | ||||||
| using System.Net; | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Class representing the server | ||||||
| /// </summary> | ||||||
| public class Server | ||||||
| { | ||||||
| private readonly int port; | ||||||
|
|
||||||
| private readonly CancellationTokenSource source = new(); | ||||||
|
|
||||||
| public CancellationTokenSource GetSource => source ; | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| /// <summary> | ||||||
| /// Сonstructor | ||||||
| /// </summary> | ||||||
| /// <param name="port">port</param> | ||||||
| public Server(int port) | ||||||
| { | ||||||
| this.port = port; | ||||||
| } | ||||||
|
|
||||||
| /// <summary> | ||||||
| /// Function to start the server (it will start listening for connections from clients) | ||||||
| /// </summary> | ||||||
| /// <returns></returns> | ||||||
| public async Task Start() | ||||||
| { | ||||||
| var tcpListener = new TcpListener(IPAddress.Any, port); | ||||||
|
|
||||||
| // Слушаем порт | ||||||
| tcpListener.Start(); | ||||||
|
|
||||||
| while (!source.Token.IsCancellationRequested) | ||||||
| { | ||||||
| // Блокируем поток до установления соединения | ||||||
| var acceptedSocket = await tcpListener.AcceptSocketAsync(); | ||||||
| // Поток для записи и чтения в полученный сокет | ||||||
| using var newtworkStream = new NetworkStream(acceptedSocket); | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. networkStream |
||||||
| Task a = Task.Run(() => SendMessage(newtworkStream)); | ||||||
| Task b = Task.Run(() => GetMessage(newtworkStream)); | ||||||
|
Comment on lines
+43
to
+44
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Их бы запоминать и подождать в конце метода |
||||||
| if (source.IsCancellationRequested) { | ||||||
| acceptedSocket.Close(); | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| tcpListener.Stop(); | ||||||
| } | ||||||
|
|
||||||
| // Принять сообщение | ||||||
| private async Task GetMessage(NetworkStream stream) | ||||||
| { | ||||||
| using var streamReader = new StreamReader(stream); | ||||||
| var data = (await streamReader.ReadLineAsync()); | ||||||
| while (data != "exit") | ||||||
| { | ||||||
| Console.WriteLine($"{data}"); | ||||||
| data = (await streamReader.ReadLineAsync()); | ||||||
|
|
||||||
| if (source.IsCancellationRequested) | ||||||
| { | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| source.Cancel(); | ||||||
| } | ||||||
|
|
||||||
| // Отправить сообщение | ||||||
| private async Task SendMessage(NetworkStream stream) | ||||||
| { | ||||||
| using var streamWriter = new StreamWriter(stream) { AutoFlush = true }; | ||||||
| var data = Console.ReadLine(); | ||||||
| while (data != "exit") | ||||||
| { | ||||||
| await streamWriter.WriteLineAsync($"{data}"); | ||||||
|
|
||||||
| if (source.IsCancellationRequested) { | ||||||
| break; | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| source.Cancel(); | ||||||
| } | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net6.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| </Project> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| namespace Test2Tests; | ||
|
|
||
| using Server; | ||
| using System.Net; | ||
|
|
||
| public class Tests2Tests | ||
| { | ||
| Server? server; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. private |
||
| CancellationTokenSource cancelTokenSource = new(); | ||
|
|
||
| [SetUp] | ||
| public void Setup() | ||
| { | ||
| var server = new Server(10000); | ||
| server.Start(); | ||
| } | ||
|
|
||
| [Test] | ||
| public void Test1() | ||
| { | ||
|
|
||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. :(. Впрочем, подозреваю, что Вы всю пару разбирались, почему клиент не запускается |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net6.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
|
|
||
| <IsPackable>false</IsPackable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.1.0" /> | ||
| <PackageReference Include="NUnit" Version="3.13.3" /> | ||
| <PackageReference Include="NUnit3TestAdapter" Version="4.2.1" /> | ||
| <PackageReference Include="NUnit.Analyzers" Version="3.3.0" /> | ||
| <PackageReference Include="coverlet.collector" Version="3.1.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Test2\Test2.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| global using NUnit.Framework; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Свойства обычно не именуют с Get