【问题标题】:NoSuchElementException when setting a timeout on the socket在套接字上设置超时时出现 NoSuchElementException
【发布时间】:2011-05-13 01:38:12
【问题描述】:

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

谢谢

【问题讨论】:

    标签: java sockets timeout java.util.scanner


    【解决方案1】:

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

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

    有关异常的详细信息,您可以查看:

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

    希望对您有所帮助 :) 干杯!

    【讨论】:

    • 在读取 _in 之前使用“hasNextLine()”条件不会引发 NoSuchElementException,也不会引发 InterruptedIOException
    • 我想我会在 NoSuchElementException 中处理超时异常,除非你有更好的解决方案:)
    • 'hasNextLine()' 不会抛出 NoSuchElementException。如果扫描仪关闭,它将抛出 IllegalStateException。在调用 _in.nextLine() 之前,您可能应该检查:_in.hasNextLine()。希望它有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2018-06-21
    • 1970-01-01
    • 2012-04-20
    • 2012-11-12
    • 2019-07-22
    相关资源
    最近更新 更多