KansaiRobot KansaiRobot - 1 year ago 361
C# Question

TcpClient: How do I close and reconnect it again?

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


Then I create a NetworkStream with


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?

Console.WriteLine("Closing the socket");

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


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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download