cocla said:
I try to connect to server using following codes:
(smart device application)
Why does it takes 5 minutes to show the "can't connect"
message?(Users must wait for long time to know the
message.)Is there any solution to solve this problem??
PS:it takes only 5 seconds to show the message when
I use the same codes in windows application.
cocla -
Instead of waiting for the synchronous Connect() method to
timeout, you can try using the asynchronous BeginConnect() method,
then set a timer for the amount of time you want to wait for the
connection. If the timer goes off before the connection is
established, you can close the socket and go on with life (you will
need to catch the Exception the EndConnect() method will throw).
Here's a small code snippet using this technique:
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(
IPAddress.Parse("192.168.0.1",9050);
IAsyncResult ar = sock.BeginConnect(iep,
new AsyncCallback(ConnectedMethod),sock);
if (ar.AsyncWaitHandle.WaitOne(5000, false))
{
Console.WriteLine("Connected");
// the socket is connected to the remote site, continue...
} else
{
Console.WriteLine("Not Connected");
sock.Close(); //this forces the EndConnect() to throw an
Exception
}
The WaitOne() method waits 5 seconds for the socket to connect. If
not, it closes the socket. In the ConnectedMethod() code, you need to
catch the Exception that might be thrown if the socket is closed:
void ConnectedMethod(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
try {
client.EndConnect(iar);
// if this succeeds, continue on with the socket...
} catch(SocketException) {
{
//if the socket was closed, do nothing...
}
}
Hope this gives you some ideas to use in your project.
Rich Blum - Author
"C# Network Programming" (Sybex)
http://www.sybex.com/sybexbooks.nsf/Booklist/4176
"Network Performance Open Source Toolkit" (Wiley)
http://www.wiley.com/WileyCDA/WileyTitle/productCd-0471433012.html