Java app hangs on in.hasNext();

我怕爱的太早我们不能终老 提交于 2019-12-24 10:45:30

问题


I am working on Battleship swing app that communicates through sockets.

private ServerSocket server;
private Socket connection;
private PrintWriter out;
private Scanner in;

I make a connection and setup output and input streams

out = new PrintWriter(connection.getOutputStream(), true);
in = new Scanner(connection.getInputStream());

Then user clicks on field that he thinks there is a ship, and coordinates get sent

public void sendXY(String cord)
{
    out.print(cord);
}

Then the method gets called that waits for opponents app to respond if there is a ship or not (true|false).

public void readHit()
{
    boolean k = true;
    while(k)
    {
        if(in.hasNext()) //<--app hangs at this line
        {
            Fields.hit = in.nextBoolean();
            k = false;  
        }
    }
}

But when I test this, my app hangs at first call to in.hasNext().


回答1:


The scanner is waiting for a token, the print method does not send a complete token unless String cord contains some kind of terminator. Try to use println instead.




回答2:


From JavaDoc https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNext()

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.

Looking inside sources, we can find this:

public boolean hasNext() {
    ensureOpen();
    saveState();
    while (!sourceClosed) {
        if (hasTokenInBuffer())
            return revertState(true);
        readInput();
    }
    boolean result = hasTokenInBuffer();
    return revertState(result);
}

It looks that method blocks if Source Stream is open and there are no bytes available. Try to find another alternatives to solve this problem. You could try to create new thread for every client, which will call hasNext()




回答3:


From the javadoc:

Returns true if this scanner has another token in its input. This method may block while waiting for input to scan. The scanner does not advance past any input.




回答4:


You could first test if there are bytes available in the connection inputstream:

InputStream instream = connection.getInputStream();
in = new Scanner(instream);

Then replace

if(in.hasNext())

with

if (instream.available() > 0)


来源:https://stackoverflow.com/questions/20546741/java-app-hangs-on-in-hasnext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!