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
22 changes: 22 additions & 0 deletions Test1.1/Test1.1.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test1.1", "Test1.1\Test1.1.csproj", "{E451040C-44C5-427F-9CF7-F83F90E54DFF}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test1.1.Tests", "Test1.1.Tests\Test1.1.Tests.csproj", "{E628CC17-DD0A-4658-8561-CB4C496A798D}"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Даже CI не одобряет отсутствия тестов

EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E451040C-44C5-427F-9CF7-F83F90E54DFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E451040C-44C5-427F-9CF7-F83F90E54DFF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E451040C-44C5-427F-9CF7-F83F90E54DFF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E451040C-44C5-427F-9CF7-F83F90E54DFF}.Release|Any CPU.Build.0 = Release|Any CPU
{E628CC17-DD0A-4658-8561-CB4C496A798D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E628CC17-DD0A-4658-8561-CB4C496A798D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E628CC17-DD0A-4658-8561-CB4C496A798D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E628CC17-DD0A-4658-8561-CB4C496A798D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
25 changes: 25 additions & 0 deletions Test1.1/Test1.1/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/.idea
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
60 changes: 60 additions & 0 deletions Test1.1/Test1.1/Client.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace Test1._1
{
/// <summary>
/// класс клиента
/// </summary>
public class Client
{
private TcpClient _client;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Если хоть одно поле у класса IDisposable, то и сам класс должен быть IDisposable, и у себя в Dispose вызывать Dispose всех своих IDisposable-полей. Иначе есть риск, что Dispose у них не вызовется до самого конца программы (что сродни утечке памяти).


public Client(string host, int port)
{
_client = new TcpClient(host, port);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Это сразу инициирует подключение, и если хост не ответит, приведёт к ожиданию таймаута, который в случае с TCP может быть довольно большим. И всё это время вызывающий будет заблокирован. Надо было использовать ConnectAsync, и не в конструкторе, а при старте.

}

public async Task Working()
{
while (true)
{
await Task.Run(async () =>
{
while (true) {
await Writer(_client.GetStream());
Copy link
Collaborator

Choose a reason for hiding this comment

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

Не-а, так Reader будет заблокирован. Надо было Task.WhenAny

await Reader(_client.GetStream());
}
});
}
}

private async Task Writer(NetworkStream stream)
{
await Task.Run(async () =>
{
var writer = new StreamWriter(stream) { AutoFlush = true };
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
var writer = new StreamWriter(stream) { AutoFlush = true };
using var writer = new StreamWriter(stream) { AutoFlush = true };

while (true)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Итого у Вас три (!) вложенных бесконечных цикла, тогда как работает (и нужен) только один

{
var data = Console.ReadLine();
await writer.WriteAsync(data + "\n");
}
});
}

private async Task Reader(NetworkStream stream)
{
await Task.Run(async () =>
{
var reader = new StreamReader(stream);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
var reader = new StreamReader(stream);
using var reader = new StreamReader(stream);

while (true)
{
var data = await reader.ReadLineAsync();
Console.WriteLine(data + "\n");
}
});
}
}
}
18 changes: 18 additions & 0 deletions Test1.1/Test1.1/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM mcr.microsoft.com/dotnet/runtime:5.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["Test1.1/Test1.1.csproj", "Test1.1/"]
RUN dotnet restore "Test1.1/Test1.1.csproj"
COPY . .
WORKDIR "/src/Test1.1"
RUN dotnet build "Test1.1.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Test1.1.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Test1.1.dll"]
22 changes: 22 additions & 0 deletions Test1.1/Test1.1/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using System;
using System.Threading.Tasks;

namespace Test1._1
{
class Program
{
static async Task Main(string[] args)
{
if (args.Length == 1)
{
var server = new Server(Int32.Parse(args[0]));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут лучше TryParse и проверить, что это действительно подходящий номер порта (больше 1024 и меньше 65535).

await server.Working();
}
else
{
var client = new Client(args[0], Int32.Parse(args[1]));
Copy link
Collaborator

Choose a reason for hiding this comment

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

Никто не обещал, что будет хоть один аргумент, кстати

await client.Working();
}
}
}
}
76 changes: 76 additions & 0 deletions Test1.1/Test1.1/Server.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;

namespace Test1._1
{
/// <summary>
/// класс серва
/// </summary>
public class Server
{
private int _port;
private readonly CancellationTokenSource _cancellationToken = new CancellationTokenSource();
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
private readonly CancellationTokenSource _cancellationToken = new CancellationTokenSource();
private readonly CancellationTokenSource _cancellationToken = new ();

Вы ж не на Java пишете :)

public Server(int port)
{
_port = port;
}

/// <summary>
/// метод в котором происходит отправка и принятие сообщение
/// </summary>
public async Task Working()
{
var listener = new TcpListener(IPAddress.Any, _port);
listener.Start();
var client = await listener.AcceptTcpClientAsync();
while (!_cancellationToken.IsCancellationRequested)
{
await Task.Run(async () =>
{
while (true) {
await Writer(client.GetStream());
await Reader(client.GetStream());
}
});
}
listener.Stop();
}

private async Task Writer(NetworkStream stream)
{
await Task.Run(async () =>
{
var writer = new StreamWriter(stream) { AutoFlush = true };
while (true)
{
var data = Console.ReadLine();
await writer.WriteAsync(data + "\n");
}
});
}

private async Task Reader(NetworkStream stream)
{
await Task.Run(async () =>
{
var reader = new StreamReader(stream);
while (true)
{
var data = await reader.ReadLineAsync();
Console.WriteLine(data + "\n");
if (data == "exit")
{
StopServer();
Copy link
Collaborator

Choose a reason for hiding this comment

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

Выйти из чата может только сервер, кажется :)

}
}
});
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Что-то копипаст, такое в клиенте уже было


private void StopServer()
=> _cancellationToken.Cancel();
}
}
10 changes: 10 additions & 0 deletions Test1.1/Test1.1/Test1.1.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>net5.0</TargetFramework>
<RootNamespace>Test1._1</RootNamespace>
<DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
</PropertyGroup>

</Project>