Socket is closed

Asked

Viewed 28 times

-3

I’m trying to create a very simple application, make only a TCP/IP connection using Java Socket, record the client message in a file and return the response to the client, but the last part, which would send the response to the client, is not working, returns the following error:java.net.SocketException: Socket is closed at java.base/java.net.Socket.getOutputStream(Socket.java:970) at br.com.teste.servidor.ServidorPrincipal.main(ServidorPrincipal.java:46) Can you help me? Follow the codes.

Java client.

public static void main(String[] args)
        throws ClassNotFoundException, InterruptedException, UnknownHostException, IOException {
    Socket socket = new Socket("localhost", 30062);
    try {

        System.out.println("Conectando");
        Scanner s = new Scanner(System.in);
        System.out.print("Digite a mensagem a ser enviada para o servidor: ");
        String msg = s.nextLine();
        s.close();
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.println(msg);
        Scanner respostaServidor = new Scanner(socket.getInputStream());
        while (respostaServidor.hasNextLine()) {

            String linha = respostaServidor.nextLine();
            System.out.println(linha);
        }

        respostaServidor.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    socket.close();

}

Serviorprincipal.java

public static void main(String[] args) throws IOException {
    ServerSocket servidor = new ServerSocket(30062);
    Socket socket;
    File arquivo;
    FileWriter fw;
    Scanner s;
    String mensagem;
    BufferedWriter bw;
    try {
        System.out.println("Iniciando Servidor");

        //while (true) {
            socket = servidor.accept();
            arquivo = new File("log.txt");
            fw = new FileWriter(arquivo, true);
            s = new Scanner(socket.getInputStream());
            mensagem = LocalDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")) + " - "
                    + s.nextLine();
            System.out.println("Cliente conectado: " + socket.getInetAddress().getHostAddress());

            // Gravar arquivo
            bw = new BufferedWriter(fw);
            bw.write(mensagem);
            bw.newLine();
            bw.close();
            s.close();
            fw.close();

            // Enviar resposta
            PrintStream saidaCliente = new PrintStream(socket.getOutputStream());
            saidaCliente.println(mensagem);
            saidaCliente.close();
            socket.close();

    //  }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

1 answer

-2

Fierce talk!

Try repositioning s.close(); placing it after the Printstream exitClient = new Printstream(socket.getOutputStream());

Browser other questions tagged

You are not signed in. Login or sign up in order to post.