开发者

SocketTimeOutException while creating socket, java

开发者 https://www.devze.com 2022-12-25 02:42 出处:网络
I have created a sample java socket application. I used Socket s = new Sock开发者_JAVA技巧et(ip, port)Now it works fine. but when my internet connection is very slow that time after a long interval (

I have created a sample java socket application.

I used Socket s = new Sock开发者_JAVA技巧et(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.


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!");}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号