tap (task-based asynchronous pattern)

This commit is contained in:
2023-02-07 14:44:58 +09:00
parent cb8fba64b1
commit f74090a49e
7 changed files with 142 additions and 0 deletions

47
TAP/Server/Server.cs Normal file
View File

@@ -0,0 +1,47 @@
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
internal class Server
{
private static readonly int BUFFER_SIZE = 256;
static async Task Main(string[] args)
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 20000);
serverSocket.Bind(endPoint);
serverSocket.Listen(1000);
while (true)
{
Socket clientSocket = await serverSocket.AcceptAsync();
Console.WriteLine(clientSocket.RemoteEndPoint);
ThreadPool.QueueUserWorkItem(ReadAsync, clientSocket);
}
}
private static async void ReadAsync(object? state)
{
if (state == null)
return;
Socket clientSocket = (Socket)state;
while (true)
{
byte[] buffer = new byte[BUFFER_SIZE];
int n1 = await clientSocket.ReceiveAsync(buffer, SocketFlags.None);
if (n1 < 1)
{
Console.WriteLine("Client is disconnected...");
clientSocket.Dispose();
return;
}
Console.WriteLine(Encoding.UTF8.GetString(buffer));
}
}
}
}