0

Here a client connection that works fine. I try several implements to timeout and fail(throw an exception and close the socket if the client can't success to server. My code:

 public void connect(string IP, int port)
        {
            try
            {

                IPHostEntry host = Dns.GetHostEntry(ip);
                IPAddress ipAddress = host.AddressList[0];
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);


                sender = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);


                try
                {
                    // Connect to Remote EndPoint  
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
efrat
  • 13
  • 1
  • 4

1 Answers1

0

It is possible to solve this using the Socket.ConnectAsync method and a timer, see:

https://stackoverflow.com/a/1062628/86611

Alternatively:

https://stackoverflow.com/a/4708790/86611

Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252