4

AcceptTcpClient() prevents app from exit after I called thrd.Abort().

How to exit application when in listening?

4

2 回答 2

8

您应该能够AcceptTcpClient()通过关闭来中断对的调用TcpListener(这将导致阻塞抛出异常AcceptTcpClient()。您应该中止线程,这通常是一个非常糟糕的主意,除了一些非常具体的情况。

这是一个简短的例子:

class Program
{
    static void Main(string[] args)
    {
        var listener = new TcpListener(IPAddress.Any, 12343);
        var thread = new Thread(() => AsyncAccept(listener));
        thread.Start();
        Console.WriteLine("Press enter to stop...");
        Console.ReadLine();
        Console.WriteLine("Stopping listener...");
        listener.Stop();
        thread.Join();
    }

    private static void AsyncAccept(TcpListener listener)
    {
        listener.Start();
        Console.WriteLine("Started listener");
        try
        {
            while (true)
            {
                using (var client = listener.AcceptTcpClient())
                {
                    Console.WriteLine("Accepted client: {0}", client.Client.RemoteEndPoint);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }
        Console.WriteLine("Listener done");
    }
}

上面的代码在单独的线程上启动了一个监听器,Enter在控制台窗口上按下会停止监听器,等待监听器线程完成,然后应用程序将正常退出,不需要线程中止!

于 2013-04-25T12:39:23.657 回答
1

你可以:

使用 BeginAcceptTcpClient() 和 End.. 代替:请参阅:https ://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginaccepttcpclient(v=vs.110).aspx

或者你可以:

创建一个 TcpClient 并发送您的侦听器消息:

因此(我猜你的线程中有一个循环):

于 2017-10-26T16:03:22.363 回答