tags:

views:

90

answers:

1

Hi All, I have created a sample java socket application. I used Socket s = new Socket(ip, port) Now it works fine. but when my internet connection is very slow that time after a long interval (even if sometimes after 2 minutes) i used to get SocketTimeOutException in that line. means it gives that error while creating socket. I want the exception should be handled properly means if internet connection is very slow then if that error occurs it happens very late now . I want if this type of error occurs then it should be caught very fast means the error should not come at such a delay interval of time rather it should come immediately.

How to achieve this.

Thanks Sunil Kumar Sahoo

+1  A: 

Decrease socket timeout like:

sock.connect(new InetSocketAddress("www.google.com", 80), 500);

where 500 is timeout in milliseconds.

Here a snippet that uses Socket class:

 try { 
      InetAddress addr = InetAddress.getByName("www.google.com");
      int port = 80; SocketAddress sockaddr = new InetSocketAddress(addr, port);
      Socket sock = new Socket(); 
      int timeoutMs = 500; 
      sock.connect(sockaddr, timeoutMs); 
    } 
catch (SocketTimeoutException  e) { System.out.println("Timeout reached!");}
systempuntoout