试图强制我的应用程序关闭,TcpListener停止侦听 - stackOverflow

时间:2012-01-09 16:35:09

标签: c# sockets socketserver

当我关闭它时,我的双角色应用程序(在另一台机器上运行的“服务器”角色)无法实际关闭(在我关闭应用程序后它仍然位于任务管理器的“进程”列表中)。

我不知道它是否保持“实时”,因为它的TcpListener类仍在侦听,或者TcpListener类仍在侦听,因为应用程序还没有真正关闭。

所以,我添加了两段代码:

1)这里的最后一行(listener.Stop()):

static void Server()     
{
    TcpListener listener = new TcpListener(IPAddress.Any, 51111);
    listener.Start();
    var shouldExit = false;
    while (!shouldExit)
        using (TcpClient c = listener.AcceptTcpClient())
        {
            using (NetworkStream n = c.GetStream())
            {
                string msg = new BinaryReader(n).ReadString();
                if (msg == "exit")
                    // Client told us to exit... 
                    shouldExit = true;
                BinaryWriter w = new BinaryWriter(n);
                w.Write(msg + " back atcha!");
                w.Flush(); // Must call Flush because we're not disposing the writer. 
            }
        }
    //listener.EndAcceptTcpClient; //unnecessary because AcceptTcpClient() is wrapped in a "using"?
    listener.Stop();
}

...和

2)

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Close(); // The app/process is staying "live" even after shutting down the app...maybe this will help?
        }
// but on closing the app, I got: "System.StackOverflowException was unhandled" here...?

调用Close时为什么会出现堆栈溢出?

0 个答案:

没有答案