Skip to content
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

- HomeWork4 #58

Merged
merged 6 commits into from
Oct 12, 2021
Merged

- HomeWork4 #58

merged 6 commits into from
Oct 12, 2021

Conversation

NikitaBabich26rus
Copy link
Owner

  • Added Tests
  • Added comments

- Added Tests
- Added comments
public async Task<byte[]> Get(string path)
{
var client = new TcpClient(host, port);
using (var stream = client.GetStream())

Choose a reason for hiding this comment

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

Можно using var, который без скобок

var client = new TcpClient(host, port);
using (var stream = client.GetStream())
{
var writer = 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.

Он тоже IDisposable, поэтому тоже надо using var

var writer = new StreamWriter(stream) { AutoFlush = true };
await writer.WriteLineAsync("1");
await writer.WriteLineAsync(path);
var reader = new StreamReader(stream);

Choose a reason for hiding this comment

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

И тут

{
var writer = new StreamWriter(stream) { AutoFlush = true };
await writer.WriteLineAsync("1");
await writer.WriteLineAsync(path);

Choose a reason for hiding this comment

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

Это нарушение требуемого протокола, в условии запрос пишется в одну строчку. Ваш клиент не будет работать с чужими серверами.


if (size == -1)
{
Console.WriteLine("This file does not exist.");

Choose a reason for hiding this comment

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

Нельзя прямо в клиенте выводить на консоль ничего, потому что вдруг отсутствие файла вполне ожидаемо и не надо пугать пользователя. Вывод на консоль вообще по идее должен быть только в Program

public async Task Start()
{
listener.Start();
while (!cancellationTokenSource.IsCancellationRequested)

Choose a reason for hiding this comment

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

Здесь надо CancellationToken использовать по идее

{
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream) { AutoFlush = true };
var comand = await reader.ReadLineAsync();

Choose a reason for hiding this comment

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

command

break;

default:
Console.WriteLine("Input error.");

Choose a reason for hiding this comment

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

И тоже не стоит ничего на консоль писать прямо тут, можно бросать исключение или сделать себе мини-логгер, который сюда принимать и который бы уже на консоль выводил (а лучше log4et подрубить)

}

var content = new byte[size];
await reader.BaseStream.ReadAsync(content, 0, size);

Choose a reason for hiding this comment

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

Не стоит зачитывать весь файл в память, файлы могут быть существенно больше, чем Вам бы хотелось. Принимайте поток и выводите в него, пусть он сам разберётся.

[Test]
public async Task GetWithIncorrectFileNameTest()
{
server.Start();

Choose a reason for hiding this comment

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

server.Start(); делается везде, можно было его в Before вынести

}
currentIndex++;
}
await stream.CopyToAsync(fileStream);

Choose a reason for hiding this comment

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

Не слишком надёжный способ, потому что не учитывает переданного вначале размера файла, и если соединение разорвётся посередине передачи, оно спокойно сохранит половину файла и даже не поругается. Но ладно, можно и так.

Правильнее было бы вычитывать по кусочкам в буфер, проверять, что всё ок, и скидывать на диск.

while (!cancellationTokenSource.Token.IsCancellationRequested)
{
var client = await listener.AcceptTcpClientAsync();
await Task.Run(() => Working(client));

Choose a reason for hiding this comment

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

Если здесь делается await, мы не сможем получить следующий client до того, как закончим работу с этим. Что портит многопоточность

@NikitaBabich26rus NikitaBabich26rus merged commit 9661400 into master Oct 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants