programming with esskar

Just another WordPress.com weblog

Posts Tagged ‘timeout

TcpSocket with Connection Timeout

leave a comment »

.NET does not offer the possibilty to specify an timeout when connecting to a tcp/ip server.
So here is yet another solution to get around this issue.

using System;
using System.Net;
using System.Net.Sockets;

namespace Esskar.Net {

    public class TcpSocket : Socket
    {
        public TcpSocket()
            : base(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { }

        public void Bind(IPAddress address, int port)
        {
            base.Bind(new IPEndPoint(address, port));
        }

        public void Listen()
        {
            // standard backlog is 5
            base.Listen(5);
        }

        #region Connect with timeout
        public bool Connect(string host, int port, int milliSecondsTimeout)
        {
            IPAddress ip;
            if (IPAddress.TryParse(host, out ip))
            {
                return this.Connect(ip, port, milliSecondsTimeout);
            }
            else
            {
                IPHostEntry ipHostEntry = Dns.GetHostEntry(host);
                return this.Connect(ipHostEntry.AddressList, port, milliSecondsTimeout);
            }
        }

        public bool Connect(IPAddress[] addresses, int port, int milliSecondsTimeout)
        {
            foreach (IPAddress ipaddr in addresses)
            {
                if (this.Connect(ipaddr, port, milliSecondsTimeout))
                    return true;                
            }
            return false;
        }

        public bool Connect(IPAddress ipAddress, int port, int milliSecondsTimeout)
        {
            return this.Connect(new IPEndPoint(ipAddress, port), milliSecondsTimeout);
        }        

        public bool Connect(EndPoint endPoint, int milliSecondsTimeout)
        {
            IAsyncResult ar = this.BeginConnect(endPoint, new AsyncCallback(TcpSocket.ConnectCallBack), this);
            bool retval = ar.AsyncWaitHandle.WaitOne(milliSecondsTimeout, false);
            if (!retval)
                this.Close();
            return retval && this.Connected;
        }

        private static void ConnectCallBack(IAsyncResult ar)
        {
            try
            {
                TcpSocket socket = ar.AsyncState as TcpSocket;
                socket.EndConnect(ar);
            }
            catch { }
        }

        #endregion
    }
}

Written by esskar

March 19, 2009 at 6:59 pm

Follow

Get every new post delivered to your Inbox.