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;
}
}
感谢
使用“hasNextLine()”条件读书_in前未抛出NoSuchElementException异常,无论是InterruptedIOException – outellou 2011-05-13 02:27:43
我想我会过程中NoSuchElementException异常里面的超时异常,除非你有更好的解决办法:) – outellou 2011-05-13 02:30:30
“hasNextLine() '不会抛出NoSuchElementException。如果扫描器关闭,它将抛出IllegalStateException。在调用_in.nextLine()之前,您应该检查:_in.hasNextLine()。希望能帮助到你 :) – Vern 2011-05-14 06:57:56