2012-10-03 47 views
4

我是套接字编程的新手,并且有一段代码打开一个套接字并写入它。我将套接字的超时设置为一分钟,并且想要关闭套接字并在达到特定条件后退出。超时设置时不关闭套接字

我的代码不关闭套接字时的条件是:

@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(); 

输出:

//"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 

为什么等待第三次迭代?第三次迭代是当条件满足时,等待大约40秒后。

我在做什么错?

+0

40秒后对方发送OK。套接字在超时时不会自动关闭。不是一个真正的问题。 – EJP

回答

2

如果您的请求超时,然后关闭该捕获中的套接字,则需要捕获SocketTimeoutException(请参阅doc),因为即使超时,套接字仍然有效。

+0

我不想赶上例外。我想在一段时间内遇到一个条件时关闭套接字(看看在这段时间内是否为cond)即使你的套接字超时仍然有效 – PermGenError

+0

你调试过它,看它是否到达'socket.close()'? – talnicolas

+0

是的,它达到了它.. lemme张贴我的输出,以清除 – PermGenError

1

这里有几个问题,但我认为最主要的是你没有正确关闭套接字。这应该在封装插槽的try块的finally块中,而不在其自己的try块中。