0

我有一段代码可以在 TCP 端口上“侦听”,并且无论发送什么,都只会返回一个字符串。问题是客户端只是在测试端口是否处于活动状态然后断开连接。此时我会抛出一个错误。无法访问已处置的对象对象名称:“System.Net.Socket.NetworkSystem”

我认为问题在于这段代码在一个线程上,当连接关闭时,while循环引用了一个已处理的对象......当客户端关闭连接时,我应该如何防止错误触发?

  //Cretae listener to accept client connections
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
        int bytesRcvd; // Received byte count
        while (ServiceRunning)  // Run forever, accepting and servicing connections
        {
            try
            {
                // Receive until client closes connection, indicated by 0 return value
                int totalBytesEchoed = 0;

//I THINK THIS IS WHERE THE PROBLEM IS .. THE CLIENTSTREAM.READ???

                while (((bytesRcvd = clientStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) && (ServiceRunning))
                {
                    clientStream.Write(responseBytes, 0, responseBytes.Length);
                    WriteEventToWindowsLog("GSSResponderService", "Received "+System.Text.Encoding.UTF8.GetString(rcvBuffer), System.Diagnostics.EventLogEntryType.Information);
                    totalBytesEchoed += bytesRcvd;
                }

                WriteEventToWindowsLog("GSSResponderService", "Responded to " + totalBytesEchoed.ToString() + " bytes.", System.Diagnostics.EventLogEntryType.Information);


                // Close the stream and socket. We are done with this client!
                clientStream.Close();
                tcpClient.Close();

            }
            catch (Exception e)
            {
//THIS IS GETTING TRIGGERED WHEN A CONNECTION IS LOST
                WriteEventToWindowsLog("GSSResponderService", "Error:" + e.Message, System.Diagnostics.EventLogEntryType.Error);
                clientStream.Close();
                tcpClient.Close();
                break;
            }
        }
    }
4

1 回答 1

0

根据 MSDN,NetworkStream类的Read方法在底层 Socket 关闭时抛出IOException ,在 NetworkStream 关​​闭或从网络读取失败时抛出ObjectDisposedException 。Write方法会抛出相同的异常。

因此,捕获这两种异常类型并在异常处理程序中采取适当的措施就足够了。

    TcpClient tcpClient = (TcpClient)client;
    NetworkStream clientStream = tcpClient.GetStream();

    byte[] rcvBuffer = new byte[BUFSIZE]; // Receive buffer
    int bytesRcvd; // Received byte count
    while (ServiceRunning)  // Run forever, accepting and servicing connections
    {
        try
        {
            // Receive until client closes connection, indicated by 0 return value
            int totalBytesEchoed = 0;

            try
            {
                while (((bytesRcvd = clientStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) && (ServiceRunning))
                {
                    clientStream.Write(responseBytes, 0, responseBytes.Length);
                    WriteEventToWindowsLog("GSSResponderService", "Received "+System.Text.Encoding.UTF8.GetString(rcvBuffer), System.Diagnostics.EventLogEntryType.Information);
                    totalBytesEchoed += bytesRcvd;
                }
            }
            catch(IOException)
            {
                //HERE GOES CODE TO HANDLE CLIENT DISCONNECTION
            }
            catch(ObjectDisposedException)
            {
                //HERE GOES CODE TO HANDLE CLIENT DISCONNECTION
            }

            WriteEventToWindowsLog("GSSResponderService", "Responded to " + totalBytesEchoed.ToString() + " bytes.", System.Diagnostics.EventLogEntryType.Information);


            // Close the stream and socket. We are done with this client!
            clientStream.Close();
            tcpClient.Close();

        }
        catch (Exception e)
        {
            WriteEventToWindowsLog("GSSResponderService", "Error:" + e.Message, System.Diagnostics.EventLogEntryType.Error);
            clientStream.Close();
            tcpClient.Close();
            break;
        }
    }
}
于 2012-04-11T18:53:44.493 回答