2011-05-13 3 views
0

클라이언트가 읽을 때 시간 초과를 설정하려고합니다. 루틴은 InterruptedIOException을 던지기로되어 있지만, 대신에 NoSuchElementException을 throw합니다. System.out.println("echo: " + _in.nextLine()); 무엇이 잘못 되었나요? NoSuchElementException 소켓에서 시간 초과를 설정할 때

내 메도

public void startUserInput() 
{ 
    try { 
     _out = new PrintWriter(_echoSocket.getOutputStream(), true); 
     _in = new Scanner(new InputStreamReader(_echoSocket.getInputStream())); 

     Scanner stdIn = new Scanner(new InputStreamReader(System.in)); 
     System.out.print("Input: "); 
     while (stdIn.hasNextLine()) { 
      _out.println(stdIn.nextLine()); 
      System.out.println("echo: " + _in.nextLine()); 
      System.out.print("Input: "); 
     } 
     stdIn.close(); 

    }catch (InterruptedIOException exception){ 
     System.err.println("The server is not responding " + _serverHostname); 

    } 
    catch (IOException e) { 
     System.out.println("error" + e.getLocalizedMessage()); 
    }} 

이며,이 이유는 당신이 _in.nextLine()를 호출하는 경우가 더 라인이없는에서 읽을 수 있다는 것입니다

public boolean establishConnection() 
{ 
    System.out.println ("Connecting to the host " + 
      this.getServerHostname() + " au port " + this.getServerPort()); 

    try { 
     _echoSocket = new Socket(); 
     _echoSocket = new Socket(this.getServerHostname(), this.getServerPort()); 
     _echoSocket.setSoTimeout(10000); 
     System.out.println(_echoSocket.getOutputStream()); 
     return _echoSocket.isConnected(); 

    } catch (UnknownHostException e) { 
     System.err.println("Unknown host: " + this.getServerHostname()); 
     return false; 



    } catch (IOException e) { 
     System.err.println("Error while connecting to the server : " + 
       this.getServerHostname() + ":" + this.getServerPort()); 
     return false; 
    } 
} 

감사

답변

2

내 연결입니다 Scanner 객체 _in에서 가져옵니다.

while 루프에서 수행 한 작업은 stdIn.hasNextLine()을 확인했지만 _in에 읽을 수있는 nextLine()이 있는지 확인하지 않았습니다. 예외에 대한 자세한 내용은

, 당신은 체크 아웃 할 수있다 :

http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html#nextLine()

그것이 도움이되기를 바랍니다 :) 건배!

+0

읽기 전에 'hasNextLine()'조건을 사용하여 NoSuchElementException을 throw하지 않았으며 InterruptedIOException도 표시하지 않음 – outellou

+0

더 나은 해결책이 없다면 NoSuchElementException 내부에서 시간 초과 예외를 처리 할 것입니다. :) – outellou

+0

'hasNextLine 'NoSuchElementException을 throw하지 않습니다. 스캐너를 닫으면 IllegalStateException가 throw됩니다. _in.nextLine()을 호출하기 전에 _in.hasNextLine()을 사용하여 확인해야합니다. 희망이 도움이 :) – Vern

관련 문제