Search code examples
c#tcpnetwork-programming

TcpClient established, but TcpClient.getStream() fails


My Client class for synchronous message exchange:

public class AsClient
{
    private TcpClient connection;

    public AsClient(int serverPort, String ip)
    {
        connection = new TcpClient(ip, port);
    }

    public AsMessage sendMessage(AsMessage message)
    {
        System.Diagnostics.Debug.WriteLine("Connected: " + connection.Connected);
        NetworkStream ns = connection.GetStream();

        StreamReader reader = new StreamReader(ns);
        StreamWriter writer = new StreamWriter(ns);

        // Send Message:
        String msgToSendEncoded = message.encode();
        writer.WriteLine(msgToSendEncoded);
        writer.WriteLine("\n"); // each message is terminated by a paragraph
        writer.Flush();

        // Receive Message:
        String msgReceivedRaw = reader.ReadLine();
        AsMessage response = AsMessage.decode(msgReceivedRaw);

        reader.Dispose();
        writer.Dispose();

        ns.Close();

        return response;
    }
}

If I debug this application, the first message sent and response received works perfectly well, but as soon as I want to send the second message, TcpClient.getStream() fails with the InvalidOperationException, which states that the connection is not established anymore.

The problem is that I am not actively closing the connection anywhere. If I put connection.Connect(host,port) before calling getStream(), it fails with the exception that the socket is still connected, even though connection.Connected is false.

Any ideas to solve this issue?


Solution

  • As I have experience Dispose close the underlying stream.

    So you close the connection on the Dispose.