Tengo un problema en un programa que estoy haciendo en java.
Estoy usando sockets para hacer una conexión cliente/servidor con la intención de que el servidor tenga un arraylist donde voy almacenando un nombre y un stock desde el cliente.
El servidor implementa una clase con threads para que se puedan conectar varios clientes simultáneamente.
Además de esto, el servidor tiene un switch que lo uso como menú para poder consultar, dar de alta o dar de baja un producto.
El problema está en que cuando elijo una opción, es como si no se ejecutara el break, es decir, no vuelve atrás para elegir otra opción.
Os dejo el código por si alguien puede ayudar, lo agradecería muchísimo. Un saludo.
Edición: He modificado el programa y ya funciona correctamente, pero hay un pequeño detalle y es que cuando pongo una opción incorrecta no salta el mensaje de default, es decir, no me muestra "Opción incorrecta". Edito las clases java aqui posteadas.
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);
}
}
}
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);
}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);
}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();
break;
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();
break;
case 3:
continue;
}
case 5:
System.out.println(laIP+": se ha desconectado.");
bw.write("Desconectado.");
bw.newLine();
bw.flush();
System.exit(0);
default:
bw.write("Opcion incorrecta.");
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);
}
}
}
}