NetworkStream connection is closed automatically

My application opens a NetworkStream and StreamWriter to send HL7 messages to the service. This service receives HL7 messages and ALWAYS sends an acknowledgment. I am having the following problem: after sending HL7 messages (which work, I tested them), I try to use s StreamReader to get an acknowledgment from the service, but it throws the "Data stream unreadable" argument to be thrown. I was debugging my code and found out that the connection was closed after using the StreamWriter block and so 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 closing because I want to read the acknowledgment that the client sends back after receiving HL7 messages?

+3


source to share


1 answer


Solved: The StreamWriter inside the use block also closed the underlying stream.

Solution: Tell Streamwriter to keep the connection open.



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

      

+4


source







All Articles