How to set up TcpListener to always listen and acc

2019-01-17 00:43发布

Here's my server app:

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();
    }
}

From what it looks like, it's already always listening while running, but I'm still asking that to specify that I'd like both always-listening and multiple connection support.

How can I modify this to constantly listen while also accepting multiple connections?

2条回答
疯言疯语
2楼-- · 2019-01-17 01:27

The socket on which you listen for incoming connections is commonly referred to as the listening socket. When the listening socket acknowledges an incoming connection, a socket commonly referred to as a child socket is created that effectively represents the remote endpoint.

In order to handle multiple client connections simultaneously, you will need to spawn a new thread for each child socket on which the server will receive and handle data. Doing so will allow for the listening socket to accept and handle multiple connections as the thread on which you are listening will no longer be blocking or waiting while you wait for incoming data.

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();
}
查看更多
We Are One
3楼-- · 2019-01-17 01:36

I had a similar problem today, and solved it like this:

while (listen) // <--- boolean flag to exit loop
{
   if (listener.Pending())
   {
      Thread tmp_thread = new Thread(new ThreadStart(() =>
      {
         string msg = null;

         clt = listener.AcceptTcpClient();

         using (NetworkStream ns = clt.GetStream())
         using (StreamReader sr = new StreamReader(ns))
         {
            msg = sr.ReadToEnd();
         }

         Console.WriteLine("Received new message (" + msg.Length + " bytes):\n" + msg);
      }
      tmp_thread.Start();
   }
   else
   {
       Thread.Sleep(100); //<--- timeout
   }
}

My loop did not get stuck on waiting for a connection and it did accept multiple connections.

查看更多
登录 后发表回答