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?
source share