2011-05-13 31 views
0

我想在客戶端讀取時設置超時。該例程應該拋出InterruptedIOException,但它會拋出NoSuchElementException 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()); 
    }} 

,這是我的連接

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

的原因是,當你調用_in.nextLine()沒有線被從讀從掃描儀對象_in。

你在while循環中做的是檢查stdIn.hasNextLine(),但是你沒有檢查_in是否有可以讀取的nextLine()。

該異常的詳細信息,你可以檢查出:

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

希望它能幫助:)乾杯!

+0

使用「hasNextLine()」條件讀書_in前未拋出NoSuchElementException異常,無論是InterruptedIOException – outellou 2011-05-13 02:27:43

+0

我想我會過程中NoSuchElementException異常裏面的超時異常,除非你有更好的解決辦法:) – outellou 2011-05-13 02:30:30

+0

「hasNextLine() '不會拋出NoSuchElementException。如果掃描器關閉,它將拋出IllegalStateException。在調用_in.nextLine()之前,您應該檢查:_in.hasNextLine()。希望能幫助到你 :) – Vern 2011-05-14 06:57:56