C# TCP/IP, Client with reconnect and timeout

Markus Freitag 3,791 Reputation points
2023-01-26T16:52:34.92+00:00

Hello,

I am looking for a good example how to create a client.

There should be a timeout if no connection could be created. Then until 3 times automatic retry.

If there is no response after the request, there should be error message, timeout.

The request is XML <root> I.e. only when the characters <\root> is received, the received message is ready.

That's what I found, all without error handling, reconnection. Do you know a good example?

https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/sockets/socket-services

http://csharp.net-informations.com/communications/csharp-socket-programming.htm

I try this, without without success.

Client_Not_possible__001_

public partial class frmDelegateEvents : Form
{
        Person Test;
        Server MyServer;

        Socket client;
        AddressFamily ipEndPoint;

Sync zu async not possible. Maybe button (WinForms) problem.

  Start Element <root> read until </root> or timeout after 2 seconds.

I press a button and want to start the client.

https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient

How do I correctly call EndConnect? Parameter EndConnect(IAsyncResult ar)


private class State
{
	public TcpClient Client { get; set; }
	public bool Success { get; set; }
}

public TcpClient Connect(string hostName, int port, int timeout)
{
	var client = new TcpClient();

	//when the connection completes before the timeout it will cause a race
	//we want EndConnect to always treat the connection as successful if it wins
	var state = new State { Client = client, Success = true };

	IAsyncResult ar = client.BeginConnect(hostName, port, EndConnect, state);
	state.Success = ar.AsyncWaitHandle.WaitOne(timeout, false);

	if (!state.Success || !client.Connected)
		throw new Exception("Failed to connect.");

	return client;
}

void EndConnect(IAsyncResult ar)
{
	var state = (State)ar.AsyncState;
	TcpClient client = state.Client;

	try
	{
		client.EndConnect(ar);
	}
	catch { }

	if (client.Connected && state.Success)
		return;

	client.Close();
}
Developer technologies C#
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.