如何设置 TcpListener 始终监听和接受多个连接? [英] How to set up TcpListener to always listen and accept multiple connections?

查看:25
本文介绍了如何设置 TcpListener 始终监听和接受多个连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的服务器应用程序:

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

如您所见,它始终在工作时进行侦听,但我想指定我希望该应用能够同时侦听并支持多个连接.

As you can see , it always listens while working , but I would like to specify that I want the app be able to listen and to have multiple connections support in the same time.

我如何修改它以在接受多个连接的同时不断收听?

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

推荐答案

  1. 您要侦听传入连接的套接字通常称为侦听套接字.

侦听套接字确认传入连接时,通常称为子套接字 被创建来有效地代表远程端点.

When the listening socket acknowledges an incoming connection, a socket that 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 the 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();
}

这篇关于如何设置 TcpListener 始终监听和接受多个连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆