eap (event-based asynchronous programming)
This commit is contained in:
61
EAP/Client/Client.cs
Normal file
61
EAP/Client/Client.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
|
||||
namespace Client;
|
||||
|
||||
internal class Client
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
|
||||
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 20000);
|
||||
|
||||
SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
|
||||
arg.RemoteEndPoint = endPoint;
|
||||
arg.Completed += ConnectCompleted;
|
||||
bool pending = socket.ConnectAsync(arg);
|
||||
if (!pending)
|
||||
ConnectCompleted(socket, arg);
|
||||
|
||||
while (true)
|
||||
{
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
private static void ConnectCompleted(object? sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
if (sender == null || e == null)
|
||||
return;
|
||||
|
||||
Socket socket = (Socket)sender;
|
||||
e.Dispose();
|
||||
|
||||
string str = Console.ReadLine() ?? string.Empty;
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(str);
|
||||
|
||||
SocketAsyncEventArgs arg = new SocketAsyncEventArgs();
|
||||
arg.SetBuffer(buffer, 0, buffer.Length);
|
||||
arg.Completed += SendCompleted;
|
||||
bool pending = socket.SendAsync(arg);
|
||||
if (!pending)
|
||||
SendCompleted(socket, arg);
|
||||
}
|
||||
|
||||
private static void SendCompleted(object? sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
if (sender == null || e == null)
|
||||
return;
|
||||
|
||||
Socket socket = (Socket)sender;
|
||||
|
||||
string str = Console.ReadLine() ?? string.Empty;
|
||||
byte[] buffer = Encoding.UTF8.GetBytes(str);
|
||||
|
||||
e.SetBuffer(buffer, 0, buffer.Length);
|
||||
bool pending = socket.SendAsync(e);
|
||||
if (!pending)
|
||||
SendCompleted(socket, e);
|
||||
}
|
||||
}
|
10
EAP/Client/Client.csproj
Normal file
10
EAP/Client/Client.csproj
Normal file
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
Reference in New Issue
Block a user