开发者

NoSuchElementException when setting a timeout on the socket

I wanted to set a timeout when a client read. the routine supposed to throw an InterruptedIOException but instead it throws NoSuchElementException on System.out.println("echo: " + _in.nextLine()); what am I doing wrong ?

this is my methode

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());
    }}

and this is my connection

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;
    }
}

Thanks


The reason is that when you invoked _in.nextLine() there is no line to be read in from the from the Scanner object _in.

What you did in the while loop was to check for stdIn.hasNextLine() but you did not check if _in has a nextLine() that can be read.

For details on the exception, you can check out:

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

hope it helps :) Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜