Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Test2/Test2/Test2.sln
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
86 changes: 86 additions & 0 deletions Test2/Test2/Test2/Client.cs
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;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Свойства обычно не именуют с Get


/// <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;
}

// Принять сообщение

Choose a reason for hiding this comment

The 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());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
var data = (await streamReader.ReadLineAsync());
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};

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
using var streamWriter = new StreamWriter(stream) { AutoFlush = true};
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();
}

/// <summary>
/// Запуск клиентской части
/// </summary>
public async void Start() {

Choose a reason for hiding this comment

The 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;
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут ни одного блокирующего вызова нет — цикл, производящий миллионы задач просто


client.Close();
}
}
34 changes: 34 additions & 0 deletions Test2/Test2/Test2/Program.cs
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());

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут вышел прострел ноги — client.Start возвращает void, ждать Task.Run не на чем, и она тут же возвращает управление. Клиент закрывается, даже не успев установить соединение.

Но, честно говоря, я вообще без идей, зачем вместо await client.Start(); писать await Task.Run(() => client.Start());, который, если бы всё работало правильно, делал бы то же самое.

}
89 changes: 89 additions & 0 deletions Test2/Test2/Test2/Server.cs
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 ;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public CancellationTokenSource GetSource => source ;
public CancellationTokenSource GetSource => source;


/// <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);

Choose a reason for hiding this comment

The 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

Choose a reason for hiding this comment

The 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();
}
}
10 changes: 10 additions & 0 deletions Test2/Test2/Test2/Test2.csproj
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>
23 changes: 23 additions & 0 deletions Test2/Test2/Test2Tests/Test2Tests.cs
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;

Choose a reason for hiding this comment

The 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()
{

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

:(. Впрочем, подозреваю, что Вы всю пару разбирались, почему клиент не запускается

}
}
23 changes: 23 additions & 0 deletions Test2/Test2/Test2Tests/Test2Tests.csproj
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>
1 change: 1 addition & 0 deletions Test2/Test2/Test2Tests/Usings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using NUnit.Framework;