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

Simple FTP #5

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-dotnet@v1
with:
dotnet-version: '6.x'
dotnet-version: '7.x'
- name: Build
run: for dir in */; do cd $dir; for sln in *.sln; do dotnet build $sln; cd ..; done; done
shell: bash
Expand Down
121 changes: 121 additions & 0 deletions SimpleFTP/Client/Client.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
namespace Client;

Choose a reason for hiding this comment

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

Надо бы линтер настроить, очень ему Ваш код не нравится


using Exceptions;
using System.Net.Sockets;

/// <summary>
/// FTP client, that can process get and list queries.
/// </summary>
public class Client
{
/// <summary>
/// Gets list of files containing in the specific directory.
/// </summary>
/// <param name="host">The DNS name of the remote host to which you intend to connect.</param>
/// <param name="port">The port number of the remote host to which you intend to connect.</param>
/// <param name="pathToDirectory">Path to the needed directory.</param>
/// <returns>
/// Returns list of elements contained in the directory.
/// List also consists of pairs, where first item is the name of the element,
/// second item is a boolean value indicating, whether the element is folder or not.
/// </returns>
public async Task<List<(string, bool)>> ListAsync(string host, int port, string pathToDirectory)
{
using var client = new TcpClient();
await client.ConnectAsync(host, port);

await using var networkStream = client.GetStream();
await using var writer = new StreamWriter(networkStream);
using var reader = new StreamReader(networkStream);

var query = $"1 {pathToDirectory}";
await writer.WriteLineAsync(query);
await writer.FlushAsync();

var response = await reader.ReadLineAsync();
return response is null or "-1" ? new List<(string, bool)>() : ParseResponse(response);
}

/// <summary>
/// Downloads specific file from the server.
/// </summary>
/// <param name="host">The DNS name of the remote host to which you intend to connect.</param>
/// <param name="port">The port number of the remote host to which you intend to connect.</param>
/// <param name="pathToFile">Path to the needed file.</param>
/// <param name="destinationStream">Stream to which file bytes will be moved.</param>
/// <returns>Size of downloaded file.</returns>
/// <exception cref="DataLossException">Throws if some bytes were lost while downloading.</exception>
public async Task<long> GetAsync(string host, int port, string pathToFile, Stream destinationStream)
{
var client = new TcpClient();
await client.ConnectAsync(host, port);

try
{
await using var networkStream = client.GetStream();
await using var writer = new StreamWriter(networkStream);

var query = $"2 {pathToFile}";
await writer.WriteLineAsync(query);
await writer.FlushAsync();

var sizeInBytes = new byte[8];
if (await networkStream.ReadAsync(sizeInBytes.AsMemory(0, 8)) != 8)
{
throw new DataLossException("Some bytes were lost.");
}

var size = BitConverter.ToInt64(sizeInBytes);
if (size == -1)
{
return -1;
}

await CopyStream(destinationStream, networkStream, size);

return size;
}
finally
{
client.Close();
}
}

private async Task CopyStream(Stream destinationStream, NetworkStream sourceStream, long size)
{
var bytesLeft = size;
var chunkSize = Math.Min(1024, bytesLeft);
var chunkBuffer = new byte[chunkSize];

while (bytesLeft > 0)
{
var readBytesCount = await sourceStream.ReadAsync(chunkBuffer, 0, (int)chunkSize);

if (readBytesCount != chunkSize)
{
throw new DataLossException("Data loss during transmission and reception.");
}

await destinationStream.WriteAsync(chunkBuffer, 0, (int)chunkSize);
await destinationStream.FlushAsync();

bytesLeft -= chunkSize;
chunkSize = Math.Min(chunkSize, bytesLeft);
}
}

private List<(string, bool)> ParseResponse(string response)
{
var splitResponse = response.Split(" ");
var numberOfElements = int.Parse(splitResponse[0]);
var listOfElements = new List<(string, bool)>();

for (var i = 1; i < numberOfElements * 2; i += 2)
{
var pair = (splitResponse[i], bool.Parse(splitResponse[i + 1]));
listOfElements.Add(pair);
}

return listOfElements;
}
}
20 changes: 20 additions & 0 deletions SimpleFTP/Client/Client.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>11</LangVersion>

<NoWarn>$(NoWarn),SA1633,SA1200,SA1101,SA1309</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions SimpleFTP/Client/Exceptions/DataLossException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
namespace Client.Exceptions;

/// <summary>
/// The exception that is thrown in case of data loss.
/// </summary>
[Serializable]
public class DataLossException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="DataLossException"/> class.
/// </summary>
public DataLossException()
{
}

/// <summary>
/// Initializes a new instance of the <see cref="DataLossException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
public DataLossException(string message)
: base(message)
{
}

/// <summary>
/// Initializes a new instance of the <see cref="DataLossException"/> class.
/// </summary>
/// <param name="message">Exception message.</param>
/// <param name="inner">Inner exception.</param>
public DataLossException(string message, Exception inner)
: base(message, inner)
{
}
}
65 changes: 65 additions & 0 deletions SimpleFTP/Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
var host = args[0];
var port = int.Parse(args[1]);

var client = new Client.Client();

while (true)
{
var query = Console.ReadLine();
if (query == null)
{
break;
}

var queryArray = query.Split(" ");

if (queryArray.Length == 1
&& queryArray[0] == "-stop")
{
break;
}

if (queryArray.Length != 2)
{
Console.WriteLine("Invalid query.");
}

switch (queryArray[0])
{
case "-list":
{
var response = await client.ListAsync(host, port, queryArray[1]);
foreach (var element in response)
{
Console.WriteLine(element);
}

break;
}

case "-get":
{
var path = string.Empty;

while (true)
{
Console.WriteLine("Path to save:");
path = Console.ReadLine();

if (File.Exists(path))
{
Console.WriteLine("File already exists.");
continue;
}

break;
}

var file = new FileStream(path ?? throw new ArgumentNullException(), FileMode.Open);
var response = await client.GetAsync(host, port, queryArray[1], file);
Console.WriteLine(response);

break;
}
}
}
Loading