Click here to Skip to main content
15,921,697 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a situation where clients are sometimes not available and I am connecting to them with TcpClient. Connect - if they aren't available, a SocketException is thrown and all is well.

The problem I'm running into is that I can't set the timeout of the connect command - it takes far too long for the situation I'm using it in. How do I set this?
Posted
Updated 22-Feb-11 0:47am
v2
Comments
Ed Nutting 22-Feb-11 6:47am    
Edited to remove pre blocks and improve grammer.

Hi there, we had this question only yesterday I believe. It is a common problem that you can't actually set the timout. Please see the following question and use answer 2:
Wait for some specfic time if any response doesn't come cancel an event[^]
 
Share this answer
 
Comments
D.Ajay 22-Feb-11 8:06am    
Sir,Can u send me the sample code for this question...
Ed Nutting 22-Feb-11 8:17am    
Unfortunately I do not have code for this, simply the concept though code would look somthing like the following: (no garuntees that it will work, i have just cobbled it together from other code I have lieing around)

(using System.Threading;)


AsyncCallback ConnectedCallback;

Connected = false;
ManualResetEvent ConnectEvent = new ManualResetEvent(false);

int Timeout = 2000;

public bool Connect(int Port)
{
try
{
Connected = false;
ConnectEvent.Reset();

ConnectedCallback = new AsyncCallback(Connected);
TheSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TheSocket.BeginConnect(Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(), Port, ConnectedCallback, null);

ConnectEvent.WaitOne(Timeout);

return Connected;
}
catch
{
}
}

private void Connected(IAsyncResult result)
{
try
{
TheSocket.EndConnect(result);
Connected = true;
ConnectEvent.Set();
}
catch (Exception e)
{
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900