Blocos Scanner.nextLine () ao usar InputStream de Socket
Quando recebo dados usandoSocket.getInputStream()
diretamente (sem algum tipo de interface como o Scanner), ele não bloqueia. Mas, quando tento usar um scanner (semelhante à forma como recebemos Strings deSystem.in
), ele faz. Fiquei me perguntando o motivo disso e como o InputStream fornecido por um soquete conectado é diferente doInputStream in
noSystem
.
O cliente usado para teste (usado para os dois servidores)
O código que trava:
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(15180);
Socket socket = ss.accept();
Scanner scanner = new Scanner(socket.getInputStream());
//read data from client
while(true) {
String data = scanner.nextLine();
System.out.println("Received data!");
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
O código que não bloqueia:
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(15180);
Socket socket = ss.accept();
//read data from client
while(true) {
int data = socket.getInputStream().read();
System.out.println("Received data!");
}
}catch(IOException e) {
e.printStackTrace();
}
}
}