-
Notifications
You must be signed in to change notification settings - Fork 0
3 semestr kr1 #24
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
base: master
Are you sure you want to change the base?
3 semestr kr1 #24
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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 |
| 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> |
| 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) | ||||||||
| { | ||||||||
|
|
||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. После |
||||||||
| if (args == null || args.Length > 2 || args.Length == 0) | ||||||||
| { | ||||||||
| throw new ArgumentException(); | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||
| if (!correct) | ||||||||
| { | ||||||||
| throw new ArgumentException(); | ||||||||
| } | ||||||||
| if (args.Length == 1) | ||||||||
| { | ||||||||
| var server = new ServerAndClient(8888); | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||||||||
| } | ||||||||
| } | ||||||||
| } | ||||||||
| 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; | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Веб-сокеты тут лишние |
||
|
|
||
| namespace _3SemestrKr1; | ||
|
|
||
| public class ServerAndClient | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Хм, в таком виде это то же самое, что и |
||
| { | ||
| _socket.Shutdown(SocketShutdown.Both); | ||
| if (_client != null) | ||
| { | ||
| _client.Close(); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это в современном .NET можно не писать. Компилятор сам поймёт по телу программы, что Main надо сгенерировать асинхронным