Ale
Ale

Reputation: 3

how can I sent after I read a message using java sockets?

I have this socket that stop working when I want to send a message using StreamOutput AFTER i already use an inputOutstream, first it receives a message then I analyzed it and finally if it has 'errors' I have to send them back to the client.

Sends the message if I delete everything related to PrintWriter and the part where something is sent.

heres the code:

    public static void main(String[] args) throws IOException, JSONException {
        sjf.setVisible(true);

        logger.info("Starting server...");
        sjf.agregarLog("Iniciando servidor");

        ServerSocket serverSocket = new ServerSocket(8080);
        logger.info("Server started on port {}", serverSocket.getLocalPort());

        while (true) {
            Socket clientSocket = serverSocket.accept();
            logger.info("Accepted connection from {}", clientSocket.getInetAddress().getHostAddress());
            sjf.agregarLog("Se acepto conexion");
            
             // Create a PrintWriter and write output data
            OutputStream outputStream = clientSocket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream, true);

            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            

            StringBuilder messageBuilder = new StringBuilder(); // Usamos un StringBuilder para concatenar todas las
            // líneas
            String line;
            while ((line = reader.readLine()) != null) { // Leer todas las líneas disponibles
                messageBuilder.append(line);
                messageBuilder.append("\n"); // Agregar el carácter '\n' de vuelta para separar las líneas
            }
            String message = messageBuilder.toString(); // Convertir el StringBuilder a una cadena

            logger.info("Received message from {}: {}", clientSocket.getInetAddress().getHostAddress(), message);
            peti = message;
            sjf.agregarLog(peti);

            // Escribimos el JSON a un archivo
            File file = new File("/archivo.json");
            PrintWriter fileWriter = new PrintWriter(file);
            fileWriter.write(message);
            fileWriter.close();

            // analizar
            sjf.agregarLog("Se mando nuevo mensaje");
            aux = false;
            lista = new Lista(); // reiniciar lista de errores
            analizarMensaje();
           
// this is the part that makes the code don't work!
            if (aux == true) {
                printWriter.println(xml + "\n");
            } else {
                printWriter.println("THERES NO ERRORS YET" +"\n" );
            }
            printWriter.flush(); // flush the PrintWriter to ensure all data is sent
            printWriter.close();

        }

    }

Upvotes: 0

Views: 47

Answers (0)

Related Questions