Svajs Svajs -4 years ago 91
Java Question

Java app hangs on in.hasNext();

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().

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download