Socket does not close when setting timeout

I am new to socket programming and a piece of code that opens a socket and writes to it. I set the timeout for the socket as one minute and want to close the socket and exit after a certain condition is reached.

My code does not close the socket when the condition is met:

@Override public void run() { Socket socket =null; PrintWriter writer = null; BufferedReader reader = null; String host = ServiceProperties.getInstance().getControllerHost(); String port = "1234; String info=""; // TODO Auto-generated method stub try { socket = new Socket(host, Integer.valueOf(port)); socket.setSoTimeout(60000); writer = new PrintWriter(socket.getOutputStream(), true); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); SampleBean sBean = (SampleBean) (FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("sampleBean")); info = ControllerDAO.getInstance().getControllerAndTimeScheduleInfo(sBean.getId()); writer.println("set TimeSchedule "+ info +" value ["+str+"]"); } catch(UnknownHostException ex) { ex.printStackTrace(); } catch(IOException ex) { ex.printStackTrace(); } String line=""; try { System.out.println("BEFORE WHILE"); System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())); while((line= reader.readLine())!=null ) { System.out.println(line); if(line.contains("OK")){ System.out.println("line contains OK "); break; } try { Thread.sleep(5000); } catch(InterruptedException ex) { ex.printStackTrace(); } } System.out.println("AFTER WHILE"); System.out.println(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())); } catch(IOException ex) { ex.printStackTrace(); } try { writer.close(); reader.close(); socket.close(); } catch(IOException ex) { ex.printStackTrace(); } } }); thread.run(); 

Output:

 //"BEFORE WHILE" // 14:54:55 // prints line // //prints empty line // now it waits for like 40 seconds // line contains OK //condition met here // breakoutof the loop // "AFTER WHILE" // 14:55:55 

Why is he waiting at the third iteration? The third iteration is when the condition is met, after waiting about 40 seconds.

What am I doing wrong?

+4
source share
3 answers

You need to catch a SocketTimeoutException (see doc ) if your request expires, then close the socket in this catch, as the socket remains valid even if there is a timeout.

+2
source

There are several problems here, but I think the main thing is that you are not closing the socket properly. This should be in the finally block of the try block, which encapsulates the sockets, and not in its own try block.

+1
source

SO_TIMEOUT does not affect close (), try setting SO_LINGER.

+1
source

Source: https://habr.com/ru/post/1437593/


All Articles