C# TCP侦听器在Windows窗体中停止侦听

C# TCP侦听器在Windows窗体中停止侦听,c#,C#,我正在使用Tcp连接在两台pc之间发送消息。它在控制台应用程序中工作正常,但在Windows窗体中,侦听器停止侦听,它不连续侦听并引发此异常 例外情况: Not listening. you must call the start() method before calling this method. 这是我的密码 代码: 您的问题很简单-您正在调用finally块中的server.Stop()。由于在try块中,您刚刚开始一个线程,因此它会立即跳到finally块 确实,您正在控制台中等待

我正在使用Tcp连接在两台pc之间发送消息。它在控制台应用程序中工作正常,但在Windows窗体中,侦听器停止侦听,它不连续侦听并引发此异常

例外情况:

Not listening. you must call the start() method before calling this method.
这是我的密码

代码:


您的问题很简单-您正在调用finally块中的
server.Stop()
。由于在try块中,您刚刚开始一个线程,因此它会立即跳到finally块

确实,您正在控制台中等待密钥,但这已经是在您停止服务器之后了

因此,首先您应该在线程内添加一个try-catch块,因为目前您不会捕获在那里发生的任何异常


第二,将
控制台.Read()
移动到
服务器.Stop()

在线程内部添加try catch后,我得到了这个异常,调用WSACancelblockingCall中断了阻塞操作。这没关系,这意味着调用
服务器时,您正在等待
服务器.acceptcpclient()
确保您在停止服务器之前正在等待按键,但在异常发生后,控件将最终阻止。如果我在此处等待,则按键后它将自动熄灭。否。在异常之前到达finally块。您需要决定程序的流程,何时退出以及退出原因由您决定。您可以将server.stop保留到退出应用程序时。
        public static  void TcpListener()
    {


            TcpListener server = null;
        try
        {


                // Set the TcpListener on port 13000.
                Int32 port = 8888;
            IPAddress localAddr = IPAddress.Parse(Getlocalip());

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);

            // Start listening for client requests.
            server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

            // Enter the listening loop.


            Thread t = new Thread(() =>
            {
                while (true)
                {
                    MessageBox.Show("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
      TcpClient client = server.AcceptTcpClient();
                    MessageBox.Show("Server Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        // Console.WriteLine("Received: {0}", data);
                        if (data == "pbrush")
                        {
                            Runprocess("start " + data);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data + " opened successfully");

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);

                        }
                        if (data == "calc")
                        {
                            Runprocess("start " + data);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data + " opened successfully");

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                        }

                        if (data.ToString() == "getmac")
                        {
                            string result = Runprocess(data, true);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(result);

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                        }

                        if (data.ToString() == "tree d:")
                        {
                            string result = Runprocess(data, true);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(result);

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                        }



                        if (data.ToString() == "ipconfig")
                        {
                            string result = Runprocess(data, true);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(result);

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                        }
                        if (data.ToString() == "facebook")
                        {
                            Runprocess("start " + data);

                            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data + " opened successfully");

                            // Send back a response.
                            stream.Write(msg, 0, msg.Length);
                        }
                        // Process the data sent by the client.
                        data = data.ToUpper();

                        Console.WriteLine("Sent");
                    }

                    // Shutdown and end connection
                    client.Close();
                }

            });
            t.IsBackground = true;
            t.Start();

        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();








    }