0

Tengo un problema con este programa java. El programa se basa en sockets cliente/servidor, la función es usar un arraylist como base de datos que se encuentra en el servidor y cada cliente puede operar simultáneamente con el servidor.

El programa funciona correctamente, tiene un menú con switch para que el cliente pueda elegir entre varias opciones, el problema es que al usar la opción salir me genera un error, aunque igualmente funciona y el cliente se desconecta del servidor.

Dejo aquí el código de las clases por si alguien puede ayudar.

HiloParaAntenderUnCliente

package servidor;

import java.io.*;
import java.net.Inet4Address;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HiloParaAntenderUnCliente extends Thread{
        ArrayList<Productos> productos = new ArrayList<Productos>();
    Iterator<Productos> lista= null;
    Socket sk;
    public HiloParaAntenderUnCliente(Socket sk){
        this.sk = sk;
    }

    @Override
    public void run() {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = sk.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            os = sk.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            Inet4Address ip = (Inet4Address) sk.getInetAddress();
            String laIP = ip.getHostAddress();
            System.out.println(laIP+": se ha conectado.");

            while(true){    
            bw.write("1. Consultar\n2. Crear\n3. Borrar\n4. Aumentar/Disminuir Stock\n5. Salir");
            bw.newLine();
            int option;
            String linea;   
            do{
               bw.write("---");
               bw.newLine();
               bw.flush();
               linea = br.readLine();
               option = Integer.parseInt(linea);
                   if(option<1 || option>5){
                   bw.write("Elige una opcion correcta."); 
                   bw.newLine();
                   bw.flush();
               }
            }while(option<1 || option>5);

            switch(option) {

            case 1:
                if(productos.isEmpty()) {
                    bw.write("No hay productos en la lista.");
                    bw.newLine();
                    bw.flush();
                    continue;
                }
                bw.write("Lista de productos: ");
                bw.newLine();
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                bw.flush();
                break;


            case 2:
                bw.write("Indique el nombre del producto para dar de alta: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();
                bw.flush();

                String nombre = br.readLine();


                bw.write("Indique el stock del producto para dar de alta: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();

                bw.flush();
                String stock = br.readLine();

                int stock2 = Integer.parseInt(stock);
                productos.add(new Productos(nombre,stock2));
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                 bw.flush();
                break;


            case 3:
                if(productos.isEmpty()) {
                    bw.write("No hay productos en la lista.");
                    bw.newLine();
                    bw.flush();
                    continue;
                }
                bw.write("Indique el nombre del producto para dar de baja: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();
                bw.flush();
                String n = br.readLine();

                lista = productos.iterator();
                while(lista.hasNext()) {                
                    Productos p = lista.next();
                    if(n.equals(p.getNombre())) {
                        lista.remove();
                    }
                }
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                bw.flush();
                break;

            case 4:
            bw.write("1. Aumentar Stock\n2. Disminuir Stock\n3. Volver atras");
            bw.newLine();
            int option2;
            String linea2;
            do{
               bw.write("---");
               bw.newLine();
               bw.flush();
               linea2 = br.readLine();
               option2 = Integer.parseInt(linea2);
               if(option2<1 || option2>3){
                   bw.write("Elige una opcion correcta."); 
                   bw.newLine();
                   bw.flush();
               }
            }while(option2<1 || option2>3);
                switch(option2){

                    case 1:
                        if(productos.isEmpty()) {
                            bw.write("No hay productos en la lista.");
                            bw.newLine();
                            bw.flush();
                            continue;
                        }
                        bw.write("Escribe el nombre del producto para aumentar el stock.");
                        bw.newLine();
                        bw.write("---");
                        bw.newLine();
                        bw.flush();
                        String ni = br.readLine();
                        lista=productos.iterator();
                        while(lista.hasNext()) {
                            Productos p = lista.next();
                            if(ni.equals(p.getNombre())) {
                                p.setStock(p.getStock()+1);
                            }
                        }
                        lista = productos.iterator();
                        while(lista.hasNext()) {
                            Productos p = lista.next();
                            bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                            bw.newLine();
                        }
                        bw.flush();
                        continue;

                    case 2:
                        if(productos.isEmpty()) {
                            bw.write("No hay productos en la lista.");
                            bw.newLine();
                            bw.flush();
                            continue;
                        }
                        bw.write("Escribe el nombre del producto para disminuir el stock.");
                        bw.newLine();
                        bw.write("---");
                        bw.newLine();
                        bw.flush();
                String no = br.readLine();
                lista=productos.iterator();
                while(lista.hasNext()) {
                            Productos p = lista.next();
                            if(no.equals(p.getNombre())) {
                            p.setStock(p.getStock()-1);
                            }
                }
                lista = productos.iterator();
                while(lista.hasNext()) {
                            Productos p = lista.next();
                            bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                            bw.newLine();
                        }
                        bw.flush();
                        continue;

                    case 3:
                        continue;
            }

            case 5:
                System.out.println(laIP+": se ha desconectado.");
                bw.write("Desconectado.");
                bw.newLine();
                bw.flush();
            }
        }          
        } catch (IOException ex) {
            Logger.getLogger(HiloParaAntenderUnCliente.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if(is != null) is.close();
            } catch (IOException ex) {
                Logger.getLogger(HiloParaAntenderUnCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
    }
}

Cliente

package cliente;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Cliente {
    final static int PORT = 40080;
    final static String HOST = "127.0.0.1";

    public static void main(String[] args) {
        try {
            Socket sk = new Socket(HOST, PORT);

            enviarMensajesAlServidor(sk);
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void enviarMensajesAlServidor(Socket sk) {
        OutputStream os = null;
        InputStream is = null;
        try {
            os = sk.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            is = sk.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            Scanner sc = new Scanner(System.in);
            String linea;
            do{
            linea = br.readLine();
            System.out.println(linea);
            if(linea.startsWith("---")){
                linea = sc.nextLine();
                bw.write(linea);
                bw.newLine();
                bw.flush();
            }
       }while(!linea.startsWith("Desconectado."));  
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if(os != null) os.close();
            } catch (IOException ex) {
                Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }  
}

Servidor

package servidor;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Servidor {

    public static void main(String[] args) {
        final int PORT = 40080;

        try {
            ServerSocket sk = new ServerSocket(PORT);
            while(true){
                Socket socket = sk.accept();
                HiloParaAntenderUnCliente hilo = new HiloParaAntenderUnCliente(socket);
                hilo.start();
            }
        } catch (IOException ex) {
            Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }   
}

Error generado al salir

Exception in thread "Thread-0" java.lang.NumberFormatException: null
    at java.lang.Integer.parseInt(Integer.java:542)
    at java.lang.Integer.parseInt(Integer.java:615)
    at servidor.HiloParaAntenderUnCliente.run(HiloParaAntenderUnCliente.java:46)

Muchas gracias de antemano.

2 respuestas 2

2

Cuando el servidor recibe la opción 5 manda al cliente el mensaje de "Desconectado" al cliente pero no sale del while principal, por lo tanto manda el prompt y espera una opción del cliente. Como el cliente finaliza la conexión. El readline del servidor se rompe sin recibir datos por lo tanto línea es nulo y quiere extraer un entero.

Lo que tienes que hacer es que cuando el servidor recibe ma opcion 5 debe salir del while co un exit o return puesto la conversación con el cliente termino y el hilo debes terminarlo.

3
  • Hola buenas, gracias por responder, claro al poner un exit en la opción 5 todo se cierra sin problema y sin errores, pero el caso es que la clase HiloParaAntenderUnCliente.java me permite conectar varios clientes simultáneamente, por lo tanto si cierro el servidor los demás clientes que estuvieran conectados se verían afectados también.
    – Riancast
    el 28 dic. 2019 a las 20:32
  • Cada cliente que se conecta abre un hilo en el servidor. Por lo tanto , cada cliente tiene su propio hilo y no deberia afectar a los otros. Sin embargo, voy que darle una mirada más detallada a como estas haciendo este proceso. el 30 dic. 2019 a las 15:34
  • No te preocupes Juan Carlos ya lo solucione, puse la respuesta abajo, gracias por la ayuda, me sirvió de mucho ^^
    – Riancast
    el 30 dic. 2019 a las 21:04
0

He conseguido que el programa siga funcionando correctamente sin que lance errores añadiendo un return como bien decía el compañero Juan Carlos y modificando el archivo cliente.

Dejo aquí las modificaciones hechas.

HiloParaAntenderUnCliente

package servidor;

import java.io.*;
import java.net.Inet4Address;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;

public class HiloParaAntenderUnCliente extends Thread{
        ArrayList<Productos> productos = new ArrayList<Productos>();
    Iterator<Productos> lista= null;
    Socket sk;
    public HiloParaAntenderUnCliente(Socket sk){
        this.sk = sk;
    }

    @Override
    public void run() {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = sk.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            os = sk.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            Inet4Address ip = (Inet4Address) sk.getInetAddress();
            String laIP = ip.getHostAddress();
            System.out.println(laIP+": se ha conectado.");

            while(true){    
            bw.write("1. Consultar\n2. Crear\n3. Borrar\n4. Aumentar/Disminuir Stock\n5. Salir");
            bw.newLine();
            int option=0;
            String linea;
            do{
               bw.write("---");
               bw.newLine();
               bw.flush();
               linea = br.readLine();
               option = Integer.parseInt(linea);
                   if(option<1 || option>5){
                   bw.write("Elige una opcion correcta."); 
                   bw.newLine();
                   bw.flush();
                   }else if(option==5){
                       System.out.println(laIP+": se ha desconectado.");
                       return;
                   }
            }while(option<1 || option>5);

            switch(option) {

            case 1:
                if(productos.isEmpty()) {
                    bw.write("No hay productos en la lista.");
                    bw.newLine();
                    bw.flush();
                    continue;
                }
                bw.write("Lista de productos: ");
                bw.newLine();
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                bw.flush();
                break;


            case 2:
                bw.write("Indique el nombre del producto para dar de alta: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();
                bw.flush();

                String nombre = br.readLine();


                bw.write("Indique el stock del producto para dar de alta: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();

                bw.flush();
                String stock = br.readLine();

                int stock2 = Integer.parseInt(stock);
                productos.add(new Productos(nombre,stock2));
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                 bw.flush();
                break;


            case 3:
                if(productos.isEmpty()) {
                    bw.write("No hay productos en la lista.");
                    bw.newLine();
                    bw.flush();
                    continue;
                }
                bw.write("Indique el nombre del producto para dar de baja: ");
                bw.newLine();
                bw.write("---");
                bw.newLine();
                bw.flush();
                String n = br.readLine();

                lista = productos.iterator();
                while(lista.hasNext()) {                
                    Productos p = lista.next();
                    if(n.equals(p.getNombre())) {
                        lista.remove();
                    }
                }
                lista = productos.iterator();
                while(lista.hasNext()) {
                    Productos p = lista.next();
                    bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                    bw.newLine();
                }
                bw.flush();
                break;

            case 4:
            bw.write("1. Aumentar Stock\n2. Disminuir Stock\n3. Volver atras");
            bw.newLine();
            int option2;
            String linea2;
            do{
               bw.write("---");
               bw.newLine();
               bw.flush();
               linea2 = br.readLine();
               option2 = Integer.parseInt(linea2);
               if(option2<1 || option2>3){
                   bw.write("Elige una opcion correcta."); 
                   bw.newLine();
                   bw.flush();
               }
            }while(option2<1 || option2>3);
                switch(option2){

                    case 1:
                        if(productos.isEmpty()) {
                            bw.write("No hay productos en la lista.");
                            bw.newLine();
                            bw.flush();
                            continue;
                        }
                        bw.write("Escribe el nombre del producto para aumentar el stock.");
                        bw.newLine();
                        bw.write("---");
                        bw.newLine();
                        bw.flush();
                        String ni = br.readLine();
                        lista=productos.iterator();
                        while(lista.hasNext()) {
                            Productos p = lista.next();
                            if(ni.equals(p.getNombre())) {
                                p.setStock(p.getStock()+1);
                            }
                        }
                        lista = productos.iterator();
                        while(lista.hasNext()) {
                            Productos p = lista.next();
                            bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                            bw.newLine();
                        }
                        bw.flush();
                        continue;

                    case 2:
                        if(productos.isEmpty()) {
                            bw.write("No hay productos en la lista.");
                            bw.newLine();
                            bw.flush();
                            continue;
                        }
                        bw.write("Escribe el nombre del producto para disminuir el stock.");
                        bw.newLine();
                        bw.write("---");
                        bw.newLine();
                        bw.flush();
                String no = br.readLine();
                lista=productos.iterator();
                while(lista.hasNext()) {
                            Productos p = lista.next();
                            if(no.equals(p.getNombre())) {
                            p.setStock(p.getStock()-1);
                            }
                }
                lista = productos.iterator();
                while(lista.hasNext()) {
                            Productos p = lista.next();
                            bw.write("Producto: "+p.getNombre()+" --- Stock: "+p.getStock());
                            bw.newLine();
                        }
                        bw.flush();
                        continue;

                    case 3:
                        continue;
            }

            case 5:
                bw.write("Desconectado.");
                bw.newLine();
                bw.flush();
                //System.exit(0);
            }
        }          
        } catch (IOException ex) {
            Logger.getLogger(HiloParaAntenderUnCliente.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if(is != null) is.close();
            } catch (IOException ex) {
                Logger.getLogger(HiloParaAntenderUnCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }        
    }
}

Cliente

package cliente;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Cliente {
    final static int PORT = 40080;
    final static String HOST = "127.0.0.1";

    public static void main(String[] args) {
        try {
            Socket sk = new Socket(HOST, PORT);

            enviarMensajesAlServidor(sk);
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private static void enviarMensajesAlServidor(Socket sk) {
        OutputStream os = null;
        InputStream is = null;
        try {
            os = sk.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            BufferedWriter bw = new BufferedWriter(osw);

            is = sk.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            Scanner sc = new Scanner(System.in);
            String linea;

            do{
            linea = br.readLine();
            System.out.println(linea);
            if(linea==null)
            {
                System.exit(0);
            }
            if(linea.startsWith("---")){
                linea = sc.nextLine();
                bw.write(linea);
                bw.newLine();
                bw.flush();
            }
       }while(!linea.startsWith("Desconectado."));  
        } catch (IOException ex) {
            Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if(os != null) os.close();
            } catch (IOException ex) {
                Logger.getLogger(Cliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }  
}

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.