34

これは私のサーバーアプリです:

public static void Main()
{
    try
    {
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

        Console.WriteLine("Starting TCP listener...");

        TcpListener listener = new TcpListener(ipAddress, 500);

        listener.Start();

        while (true)
        {
            Console.WriteLine("Server is listening on " + listener.LocalEndpoint);

            Console.WriteLine("Waiting for a connection...");

            Socket client = listener.AcceptSocket();

            Console.WriteLine("Connection accepted.");

            Console.WriteLine("Reading data...");

            byte[] data = new byte[100];
            int size = client.Receive(data);
            Console.WriteLine("Recieved data: ");
            for (int i = 0; i < size; i++)
                Console.Write(Convert.ToChar(data[i]));

            Console.WriteLine();

            client.Close();
        }

        listener.Stop();
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e.StackTrace);
        Console.ReadLine();
    }
}

ご覧のとおり、作業中は常にリッスンしますが、アプリがリッスンできるようにし、同時に複数の接続をサポートするように指定したいと思います。

複数の接続を受け入れながら、常にリッスンするようにこれを変更するにはどうすればよいですか?

4

3 に答える 3

58
  1. 着信接続をリッスンするソケットは、一般にリスニング ソケットと呼ばれます。

  2. リッスンしているソケットが着信接続を確認すると、一般に子ソケットと呼ばれるソケットが作成され、リモート エンドポイントを効果的に表します。

  3. 複数のクライアント接続を同時に処理するには、サーバーがデータを受信して​​処理 する子ソケットごとに新しいスレッドを生成する必要があります。
    そうすることで、受信データを待機している間、待機しているスレッドがブロックまたは待機しなくなるため、待機ソケットが複数の接続を受け入れて処理できるようになります。

while (true)
{
   Socket client = listener.AcceptSocket();
   Console.WriteLine("Connection accepted.");
    
   var childSocketThread = new Thread(() =>
   {
       byte[] data = new byte[100];
       int size = client.Receive(data);
       Console.WriteLine("Recieved data: ");
       
       for (int i = 0; i < size; i++)
       {
           Console.Write(Convert.ToChar(data[i]));
       }

       Console.WriteLine();
    
       client.Close();
    });

    childSocketThread.Start();
}
于 2013-10-15T17:32:39.613 に答える