C# Source Code: Connecting to a server using a TCP Socket with a timeout
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Connecting to a server using a TCP Socket with a timeout
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, January 12, 2006
Hits:
2880
Category:
Sockets/Internet/Remote Comms
Article:
Unfortunately, there is no direct way of specifying a connection timeout (you can only specify send and receive timeouts) when using the Socket object. However, this functionality can easily be acheived using the BeginConnect method. Below is an example demonstrating how to connect a TCP socket with a connection timeout: PLEASE NOTE: If the socket does not connect within the connection timeout, this DOES NOT mean that a connection will not eventually be established. You should therefore impliment the IDisposable interface in the class which uses this code, so that you can close the socket using System; using System.Net; using System.Net.Sockets; using System.Threading; // Resolve the server IPAddress server = Dns.Resolve("localhost").AddressList[0]; // Create the endpoint (using port 21) IPEndPoint ep = new IPEndPoint(server, 21); // Create the socket Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect using a timeout (5 seconds) IAsyncResult result = socket.BeginConnect( ep, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 5000, true ); if ( !success ) { // NOTE, MUST CLOSE THE SOCKET socket.Close(); throw new ApplicationException("Failed to connect server."); } // Success //... Console.ReadLine();
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet