C# – Reconnect TCPClient after interruption

cnetsocketstcptcpclient

I have multiple instances of a client application, connecting to a main application over internet by TcpClient. (Both coded by me). So the connection is made like:

TcpClient.Connect(ip, port)

I now want this to handle various type of disconnect events:

  1. Main App (server) or a client app computer lose internet connection.

    • On resume of connection, the communication seems lost, but when I try to reconnect, I get message:
      "A connection request was made on an already connected socket"
    • So I need to close and restart the client app.
  2. Main App (server) is closed, and restarted.

    • Restarting the Main App, and then trying to reconnect the client app, results in same error as above.

So, what do I need to do? Do I need to instantiate a New TcpClient in the Client Apps, whenever such interruption occur? I haven't tried that, so don't know if that's a poor solution?

Best Answer

do I need to instantiate a New TcpClient in the Client Apps, whenever such interruption occur?

Yes. If the connection represented by the TcpClient is broken, you can't use that object for further communicating, nor can you connect it again. Create a new TcpClient object.

Your problem is likely that a NAT gateway times out your TCP connection, so nothing can get through between your server<->client, if all your client does is read from the connection, it will not discover this case, and it thinks the connection is still open.

Related Topic