C# – TcpClient: How to close and reconnect it again

ctcpclient

Hello and thanks for your help.
This time I would like to ask about TcpClient.
I have a server program and I am writing a client program.
This client uses TcpClient. It starts by creating a new client

clientSocket=new TcpClient(); 

(By the way, can this cause exceptions? just in case I put it inside a try-catch but I am not sure if that is really necessary)
Anyway, later I enter a loop and inside this loop I connect to the server

clientSocket.Connect("xx.xx.xx.xx",port);

Then I create a NetworkStream with

clientStream=clientSocket.GetStream();

and then start waiting for data from the server through Read. I know this is blocking so I also set a ReadTimeOut (say 1 second)

Anyway, so far so good.
Later if I don't receive anything from the server, I attempt to send something to it. If this keeps happening for say 3 times I want to close the connection and reconnect to the server again

(notice that a whole different problem is when the server somehow is down, cause that causes other kinds of errors in the client-perhaps I will ask about that later)

So, what do I do?

 if(clientSocket.Connected)
            {
                Console.WriteLine("Closing the socket");
                clientSocket.Close();
            }

I close the socket.
The loop is finished so I go again to the beginning and try to connect to the server.

clientSocket.Connect("xx.xx.xx.xx",port);

However this causes an error(an unhandled exception actually) "Can not access a disposed object"

So my question is How can I close and reconnect to the server again??

Thanks again for any help

Best Answer

A TcpClient instance can only be used to connect once. You can simply instantiate a new TcpClient, rather than trying to re-open a closed one.