Search code examples
c#tcpclientstreamreaderstreamwriternetworkstream

Connection of NetworkStream is closed automatically


My application opens a NetworkStream and a StreamWriter to sent HL7-messages to a service. This service receives the HL7-messages and ALWAYS sends back an acknowledgement. I have the following problem: After sending the HL7-messages (which works, I tested it) I try to use s StreamReader to receive the acknowledgement from the service but this leads to an argument exception "The datastream was not readable". I debugged into my code and found out that the connection was closed after the using-block of the StreamWriter and therefore there is nothing to read for the StreamReader.

Here is my code:

    public static void SendMessage(string message, string ip, int port)
    {
        string acknowledge;

        try
        {
            using (TcpClient client = new TcpClient(ip, port))
            {
                using (NetworkStream networkStream = client.GetStream())
                {
                    using (StreamWriter clientStreamWriter = new StreamWriter(networkStream))
                    {
                        clientStreamWriter.Write(message);
                    }

                    using (StreamReader clientStreamReader = new StreamReader(networkStream))
                    {
                        acknowledge = clientStreamReader.ReadToEnd();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Connection Problems: " + ex.ToString()); 
        }
    }

How can I stop the connection from being closed, because I want to read the acknowledgement the client sends back after receiving the HL7-messages ?


Solution

  • Solved: StreamWriter inside the using block also closed the base Stream.

    Solution: Tell the Streamwriter to leave connection open.

    public StreamWriter(
        Stream stream,
        Encoding encoding,
        int bufferSize,
        bool leaveOpen
    )