在套接字上设置超时时的NoSuchElementException

时间:2011-05-13 01:38:12

标签: java sockets timeout java.util.scanner

我想在客户端读取时设置超时。该例程应该抛出一个InterruptedIOException但是它会在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;
    }
}

由于

1 个答案:

答案 0 :(得分:2)

原因是当您调用_in.nextLine()时,没有要从Scanner对象中读取的行_in。

你在while循环中所做的是检查stdIn.hasNextLine(),但你没有检查_in是否有可以读取的nextLine()。

有关例外的详细信息,您可以查看:

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

希望它有所帮助:)干杯!