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

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.4.33403.182
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "3SemestrKr1", "3SemestrKr1\3SemestrKr1.csproj", "{AB1D2303-6545-4CCD-87E5-1E5485F7F187}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{AB1D2303-6545-4CCD-87E5-1E5485F7F187}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AB1D2303-6545-4CCD-87E5-1E5485F7F187}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AB1D2303-6545-4CCD-87E5-1E5485F7F187}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AB1D2303-6545-4CCD-87E5-1E5485F7F187}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DC079B2E-8D6D-48F5-B092-E5AA61958569}
EndGlobalSection
EndGlobal
11 changes: 11 additions & 0 deletions 3SemestrKr1/3SemestrKr1/3SemestrKr1.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>_3SemestrKr1</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

</Project>
32 changes: 32 additions & 0 deletions 3SemestrKr1/3SemestrKr1/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using _3SemestrKr1;

class Program
{
public static async Task Main(string[] args)
Comment on lines +4 to +6

Choose a reason for hiding this comment

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

Это в современном .NET можно не писать. Компилятор сам поймёт по телу программы, что Main надо сгенерировать асинхронным

{

Choose a reason for hiding this comment

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

После { пустая строка не ставится

if (args == null || args.Length > 2 || args.Length == 0)
{
throw new ArgumentException();

Choose a reason for hiding this comment

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

Main — это место, где ловят исключения, а не кидают (тут надо вывести дружественное к пользователю сообщение об ошибке, а не стек вызовов из одного фрейма и без пояснений, какой именно аргумент не понравился). Не пишите throw в Main.

}

var port = 0;
var correct = int.TryParse(args[0], out port);
Comment on lines +14 to +15

Choose a reason for hiding this comment

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

Suggested change
var port = 0;
var correct = int.TryParse(args[0], out port);
var correct = int.TryParse(args[0], out int port);

if (!correct)
{
throw new ArgumentException();
}
if (args.Length == 1)
{
var server = new ServerAndClient(8888);

Choose a reason for hiding this comment

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

Значение аргумента в этом случае игнорируется и сервер всё равно запускается на порту 8888?

await server.StartServer();
server.Talk();
}
else
{
var client = new ServerAndClient(args[1], port);
client.Talk();
}
}
}
70 changes: 70 additions & 0 deletions 3SemestrKr1/3SemestrKr1/ServerAndClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;

Choose a reason for hiding this comment

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

Веб-сокеты тут лишние


namespace _3SemestrKr1;

public class ServerAndClient

Choose a reason for hiding this comment

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

Надо комментарии

{
private static int _port;
private static TcpListener? _listener;
private static TcpClient? _client;
private static string? _ipAddress;
private static Socket? _socket;
private static NetworkStream? stream;
Comment on lines +10 to +14

Choose a reason for hiding this comment

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

Точно ли все эти поля должны быть нуллабельными? А ещё кто-то из них определённо реализует IDisposable, так что и весь класс, их содержащий, должен реализовывать IDisposable, и вызывать их Dispose у себя.


public ServerAndClient(int port)
{
_port = port;
_listener = new TcpListener(IPAddress.Any, port);
}

public async Task StartServer()
{
if (_listener == null)
{
throw new InvalidProgramException();
}
_client = await _listener.AcceptTcpClientAsync();

Choose a reason for hiding this comment

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

Вообще, все потенциально длительные (и тем более потенциально бесконечные) операции должны принимать CancellationToken.

_socket = _listener.AcceptSocket();
stream = new NetworkStream(_socket);
}

public ServerAndClient(string ipAdress, int port)
{
_port = port;
_ipAddress = ipAdress;
_client = new TcpClient(ipAdress, port);

Choose a reason for hiding this comment

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

А я бы не смешивал понятия сервера и клиента. Потому что у одного есть TcpClient, у другого TcpListener, и они никогда не могут быть не null вместе.

}

public void Talk()
{
if (_socket == null || stream == null)
{
throw new ArgumentNullException();

Choose a reason for hiding this comment

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

Но Talk() не принимает аргументов :) Тут правильнее InvalidOperationExpression

}

while (true)
{
var writer = new StreamWriter(stream);
var reader = new StreamReader(stream);
var data = reader.ReadToEnd();
if (string.Compare(data, "exit") == 0)

Choose a reason for hiding this comment

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

Хм, в таком виде это то же самое, что и data == "exit"

{
_socket.Shutdown(SocketShutdown.Both);
if (_client != null)
{
_client.Close();

Choose a reason for hiding this comment

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

Это был бы надёжный способ закрыть соединение, не реализуя никакой IDisposable, если бы не было исключений.

}
if (_listener!= null)
{
_listener.Server.Close();
}
break;
}
Console.WriteLine(reader);
var someText = Console.ReadLine();
writer.WriteLine(someText);
}
}
}