TcpClient Auto-Reconnect

What is the best way to automatically connect Tcpclient to a server when it is disconnected (for example, by the server itself)?

The code I use is:

public void ClientWork() { TcpClient client = new TcpClient(); try { try { client.Connect(ip, port); } catch(Exception ex) { logger.ErrorFormat("client.Connect: {0}", ex.Message); return false; } NetworkStream ns = client.GetStream(); byte[] buff; while (__bRunning) { buff = new byte[1000]; ns.Read(buff, 0, 1000); string line = System.Text.Encoding.Default.GetString(buff); } //ns.Close(); client.Close(); } catch(Exception e) { //Reconnect? client.Close(); client = null; return false; } } 

I am using C # .NET

+6
source share
1 answer

There are no events to receive notification of a failed connection.

There may be 2 possible solutions.

  • Poll

    . You have a separate thread that is trying to poll the socket, which is constantly running in different threads. Contact Instantly detect client disconnect from server socket

  • If you have a low level of control over the socket or an interface that uses the socket, you can try try..catch for read and write methods or try..catch for shells for read and write methods and when there is any exception that you can reconnect and try to read and write.

+1
source

Source: https://habr.com/ru/post/889444/


All Articles