Solucionado (ver solução)
Solucionado
(ver solução)
1
resposta

Console do servidor só imprime quando finaliza o cliente

No meu código, o console do servidor só está imprimindo os inputs do cliente quando é dado o enter para finalizar o cliente, e mesmo assim ele imprime tudo na mesma linha, conferi o código e está igual ao passado na aula, vou colar abaixo as 3 classes:

public class ServidorTarefas {

    public static void main(String[] args) throws IOException {

        System.out.println("--- Iniciando Servidor ---");
        ServerSocket servidor = new ServerSocket(12345);
        ExecutorService threadPool = Executors.newCachedThreadPool();

        while (true) {
            Socket socket = servidor.accept();
            System.out.println("Novo cliente aceito na porta " + socket.getPort());

            DistribuirTarefas distribuirTarefas = new DistribuirTarefas(socket);
            threadPool.execute(distribuirTarefas);
        }
    }
}
public class ClienteTarefas {

    public static void main(String[] args) throws IOException, InterruptedException {

        final Socket socket = new Socket("localhost", 12345);
        System.out.println("Conexão OK");
        Thread threadEnviaComando = new Thread(new Runnable() {

            public void run() {
                try {
                    System.out.println("Pode enviar comandos para o servidor");
                    PrintStream saida = new PrintStream(socket.getOutputStream());
                    Scanner teclado = new Scanner(System.in);
                    while (teclado.hasNextLine()) {
                        String linha = teclado.nextLine();
                        if (linha.trim().equals("")) {
                            break;
                        }
                        saida.print(linha);
                    }
                    saida.close();
                    teclado.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        Thread threadRecebeResposta = new Thread(new Runnable() {
            public void run() {
                try {
                    System.out.println("Recebendo dados do servidor");
                    Scanner respostaServidor = new Scanner(socket.getInputStream());
                    while (respostaServidor.hasNextLine()) {
                        String linha = respostaServidor.nextLine();
                        System.out.println(linha);
                    }

                    respostaServidor.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        threadEnviaComando.start();
        threadRecebeResposta.start();

        threadEnviaComando.join();

        System.out.println("Fechando socket");
        socket.close();
    }
}
public class DistribuirTarefas implements Runnable {

    private Socket socket;

    public DistribuirTarefas(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        try {
            System.out.println("Distribuindo tarefas para " + socket);
            Scanner entradaCliente = new Scanner(socket.getInputStream());
            PrintStream saidaCliente = new PrintStream(socket.getOutputStream());

            while (entradaCliente.hasNextLine()) {
                String comando = entradaCliente.nextLine();
                System.out.println(comando);
            }
            saidaCliente.close();
            entradaCliente.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

O que será que está errado? Não estou conseguindo identificar.

Exemplificando, quando eu digito o seguinte no cliente:

c1

c2

c3

Durante o input do c1, c2 e c3, no servidor não é impresso nada, mas após o enter depois de digitar o c3 (finalizando a aplicação cliente), no servidor é impresso

c1c2c3

1 resposta
solução!

Estou fechando a dúvida, identifiquei o problema, tinha um print e não um println no código do cliente.

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software