0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#のソケット通信を誤解していた話

Posted at

サーバー側では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.");
    }
}


0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?