客户端停止时异常未处理的错误 运行

Exception Unhandled error when client stops running

客户端正在通过 TCP 连接成功地向服务器发送字符串数据。当客户端停止或关闭时,服务器代码退出并在下面代码的 string theString = streamReader.ReadLine(); 行出现 'Exception Unhandled' 错误。 .

我可以使用哪些更改或方法让服务器代码正常退出连接和程序?

   static void Listeners()
        {

            Socket socketForClient = tcpListener.AcceptSocket();
            if (socketForClient.Connected)
            {
                Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
                NetworkStream networkStream = new NetworkStream(socketForClient);
                System.IO.StreamWriter streamWriter =  new System.IO.StreamWriter(networkStream);
                System.IO.StreamReader streamReader =     new System.IO.StreamReader(networkStream);

                while (true)
                {
                    string theString = streamReader.ReadLine();
                    Console.WriteLine("Message recieved by client:" + theString);
                    break;
                }
                streamReader.Close();
                networkStream.Close();
                streamWriter.Close();

            }
            socketForClient.Close();
            Console.WriteLine("Press any key to exit from server program");
            Console.ReadKey();
        }

像这样:

try {
    while (true)
    {
        string theString = streamReader.ReadLine();
        Console.WriteLine("Message recieved by client:" + theString);
    }
} catch (Exception ex) {
    Console.WriteLine("Error: " + ex.Message);
} 

正如其他人提到的,您应该使用 using 语句来帮助您处理 Disposables:

    static void Listeners()
    {
        using (Socket socketForClient = tcpListener.AcceptSocket())
        {
            if (socketForClient.Connected)
            {
                Console.WriteLine("Client:" + socketForClient.RemoteEndPoint + " now connected to server.");
                using (NetworkStream networkStream = new NetworkStream(socketForClient))
                using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream))
                using (System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream))
                {
                    try
                    {
                        while (true)
                        {
                            string theString = streamReader.ReadLine();
                            Console.WriteLine("Message recieved by client:" + theString);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                }
            }
        }
        Console.WriteLine("Press any key to exit from server program");
        Console.ReadKey();
    }