how do i get TcpListener to accept multiple connections and work with each one individually?

前端 未结 4 1382
野的像风
野的像风 2020-12-01 01:04

I have an SMTP listener that works well but is only able to receive one connection. My C# code is below and I am running it as a service. My goal is to have it runnign on a

相关标签:
4条回答
  • 2020-12-01 01:33

    You can factor out most of your code into a separate thread:

    static void Main(string[] args)
    {
        TcpListener listener = new TcpListener(IPAddress.Any , 8000);
        TcpClient client;
        listener.Start();
    
        while (true) // Add your exit flag here
        {
            client = listener.AcceptTcpClient();
            ThreadPool.QueueUserWorkItem(ThreadProc, client);
        }
    }
    private static void ThreadProc(object obj)
    {
        var client = (TcpClient)obj;
        // Do your work here
    }
    
    0 讨论(0)
  • 2020-12-01 01:35

    As per your code, you are starting one listener and receiving and processing message and closing program.

    You need to maintain a listener and TcpClient object can be passed to another function to process the message received. listener.Start();

            Console.WriteLine("Awaiting connection...");
            client = listener.AcceptTcpClient();
            Console.WriteLine("Connection accepted!");
    
    0 讨论(0)
  • 2020-12-01 01:40

    I know this is old question but I am sure many will like this answer.

    // 1
    while (listening)
    {
        TcpClient client = listener.AcceptTcpClient();
        // Start a thread to handle this client...
        new Thread(() => HandleClient(client)).Start();
    }
    
    // 2
    while (listening)
    {
        TcpClient client = listener.AcceptTcpClient();
        // Start a task to handle this client...
        Task.Run(() => HandleClient(client));
    }
    
    // 3
    public async void StartListener() //non blocking listener
    {
        listener = new TcpListener(ipAddress, port);
        listener.Start();
        while (listening)
        {
            TcpClient client = await listener.AcceptTcpClientAsync().ConfigureAwait(false);//non blocking waiting                    
            // We are already in the new task to handle this client...   
            HandleClient(client);
        }
    }
    //... in your code
    StartListener();
    //...
    //use Thread.CurrentThread.ManagedThreadId to check task/thread id to make yourself sure
    
    0 讨论(0)
  • 2020-12-01 01:44

    You almost certainly want to spin each connection into another thread. So you have the "accept" call in a loop:

    while (listening)
    {
        TcpClient client = listener.AcceptTcpClient();
        // Start a thread to handle this client...
        new Thread(() => HandleClient(client)).Start();
    }
    

    Obviously you'll want to adjust how you spawn threads (maybe use the thread pool, maybe TPL etc) and how you stop the listener gracefully.

    0 讨论(0)
提交回复
热议问题