Async Timeout events for TCP connections.

M

Mark Smith

Hi ,

Is it possible in .Net to define a async timer callback. What I am
wanting to do is declare a time-out condition that gets executed
should the something timeout.

The reason I want to do this is to handle host being down that I am
trying to connect to using TCPIP. Then after a timeout automatically
try another host and just continue trying hosts until someone accepts
a connection, varying my timeout as I loop.

Function1 (string hostname)
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(hostname, 9999);
IAsyncResult ar = sock.BeginConnect(iep, new
AsyncCallback(ConnectedMethod), sock);

Call another ASYNC routine (TryAnotherHost) that defines timer event
callback which if not cancelled executes within 15 seconds.
}

void ConnectedMethod(IAsyncResult iar)
{
Socket socket = (Socket)iar.AsyncState;
socket.EndConnect(iar);

cancel the timer???
<do all my normal stuff>
}

void TryAnotherHost (IAsyncResult iar)
{
Socket socket = (Socket)iar.AsyncState;
socket.EndConnect(iar);

socket.Close();
function1 ("another");
}

Is this possible and what routines should I review to achieve this.

Thanks

Mark
 
J

Jared Parsons [MSFT]

I'm not aware of a good way of setting a connect timeout. I'm not sure if
its possible or not.

Another option would be to asynchronously connect to multiple hosts at the
same time. Since you seem to have a list of available hosts and you just
need one that is working, this method should work for you. Do a
BeginConnect() on say 5 or so and the first one to come back successfully
wins so to speak. If any of the rest succeed then just close them. For
every one that fails while you still have not connected, create a new Socket
and call BeginConnect() for the next host

--
Jared Parson [MSFT]
(e-mail address removed)

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top