サーバー側ではlistenよりもlistener
先週で及第点までは理解できた気でいた非同期ですが学び直すと抜けが多いこと。
それ以上に根本的に勘違いがあったので正解をペタリします。
サーバー側
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class TcpServer
{
private TcpListener listener;
public TcpServer(string ipAddress, int port)
{
IPAddress localAddr = IPAddress.Parse(ipAddress);
listener = new TcpListener(localAddr, port);
}
public async Task StartListeningAsync()
{
listener.Start();
Console.WriteLine("Server started. Waiting for a connection...");
while (true)
{
TcpClient client = await listener.AcceptTcpClientAsync(); // クライアントの接続を待機
Console.WriteLine("Client connected!");
// 各クライアントを個別のタスクで処理
Task.Run(() => HandleClientAsync(client));
}
}
private async Task HandleClientAsync(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
try
{
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string receivedData = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {receivedData}");
// クライアントにレスポンスを送信
string responseData = "Message received";
byte[] responseBytes = Encoding.ASCII.GetBytes(responseData);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
Console.WriteLine("Sent: Message received");
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
finally
{
client.Close();
Console.WriteLine("Client disconnected.");
}
}
public void Stop()
{
listener.Stop();
Console.WriteLine("Server stopped.");
}
}