Foros del Web » Programación para mayores de 30 ;) » Java »

Problema Cliente - Servidor Java

Estas en el tema de Problema Cliente - Servidor Java en el foro de Java en Foros del Web. El problema es este: Estoy haciendo un cliente-servidor en java de un juego, en el cual el servidor captura dos clientes y va intercambiando las ...
  #1 (permalink)  
Antiguo 18/04/2009, 21:08
 
Fecha de Ingreso: abril-2009
Mensajes: 3
Antigüedad: 15 años
Puntos: 0
Problema Cliente - Servidor Java

El problema es este:
Estoy haciendo un cliente-servidor en java de un juego, en el cual el servidor captura dos clientes y va intercambiando las jugadas respectivas del juego entre ellos. Todo bien hasta ahí, pero yo quiero que cuando un tercer cliente se intente conectar le devuelva un error de que solo se admiten dos clientes. Hasta el momento lo único que he podido hacer es que el tercer cliente se quede esperando infinitamente, pero yo lo que quiero es que lance un error. Espero que alguien me pueda dar una sugerencia de como podría hacer eso

Este es el código que estoy usando para el servidor

Código:
import java.awt.BorderLayout;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Servidor extends JFrame {

    private String[] areaJuego1 = new String[81];
    private String[] areaJuego2 = new String[81];
    private Jugador[] jugadores;
    private ServerSocket servidor;
    private int jugadorActual;
    private final static int JUGADOR_1 = 0;
    private final static int JUGADOR_2 = 1;
    private final static String[] TURNOS = {"1", "2"};
    private ExecutorService iniciarJuego;
    private Lock lock;
    private Condition otroJugadorConectado;
    private Condition otroJugadorTurno;
    private boolean tableroCompletado1 = false;
    private boolean tableroCompletado2 = false;
    private JTextArea areaTexto;
    private int oportunidadesRestantes1 = 2/*15*/;
    private int oportunidadesRestantes2 = 2/*15*/;
    private int jugadoresListos = 0;

    public Servidor() {
        super("Servidor");

        iniciarJuego = Executors.newFixedThreadPool(2);
        System.out.println("Servidor: iniciado Ejecutor");
        lock = new ReentrantLock();
        System.out.println("Servidor: iniciado Lock");
        otroJugadorConectado = lock.newCondition();
        otroJugadorTurno = lock.newCondition();
        for (int i = 0; i < areaJuego1.length; i++) {
            areaJuego1[i] = "";
        }
        for (int y = 0; y < areaJuego2.length; y++) {
            areaJuego2[y] = "";
        }
        System.out.println("Servidor: iniciadas Areas de juego");
        jugadores = new Jugador[2];
        jugadorActual = JUGADOR_1;
        try {
            servidor = new ServerSocket(12345, 2);
        } catch (IOException ex) {
            ex.printStackTrace();
            System.exit(1);
        }
        System.out.println("Servidor: iniciado servidor");

        areaTexto = new JTextArea();
        add(areaTexto, BorderLayout.CENTER);
        areaTexto.setText("Servidor Esperando Conexiones\n");
        System.out.println("Servidor: iniciada interfaz");

        setSize(300, 300);
        setVisible(true);
    }

    public void execute() {

        while (true) {
            try {
                if (jugadoresListos < 2) {
                    jugadores[jugadoresListos] = new Jugador(servidor.accept(), jugadoresListos, false);
                    iniciarJuego.execute(jugadores[jugadoresListos]);
                    System.out.println("Servidor: Capturando Clientes");
                    jugadoresListos++;
                                    if (jugadoresListos == jugadores.length) {
                    lock.lock();
                    try {
                        jugadores[JUGADOR_1].setSuspendido(false);
                        otroJugadorConectado.signal();
                    } finally {
                        lock.unlock();
                    }
                }
                } else {
                    Jugador temp = new Jugador(servidor.accept(), 0, true);
                    iniciarJuego.execute(temp);
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                System.exit(1);
            }
        }
//        for (int i = 0; i < jugadores.length; i++) {
//            try {
//                jugadores[i] = new Jugador(servidor.accept(), i, false);
//                iniciarJuego.execute(jugadores[i]);
//                System.out.println("Servidor: Capturando Clientes");
//            } catch (IOException ex) {
//                ex.printStackTrace();
//                System.exit(1);
//            }
//        }
//        lock.lock();
//        try {
//            jugadores[JUGADOR_1].setSuspendido(false);
//            otroJugadorConectado.signal();
//        } finally {
//            lock.unlock();
//        }
    }

    private boolean juegoTerminado() {
        if (oportunidadesRestantes1 == 0 || oportunidadesRestantes2 == 0) {
            return true;
        } else {
            return false;
        }
    }

    public void mostrarMensaje(final String mensaje) {
        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {
                        areaTexto.append(mensaje);
                        System.out.println("Servidor: Mostrado Mensaje");
                    }
                });
    }

    public boolean validarJugada(int ubicacion, int jugador) {
        while (jugador != jugadorActual) {
            lock.lock();
            try {
                otroJugadorTurno.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println("Servidor: Jugador Esperando");
        }
        if (estaOcupado(ubicacion, jugador)) {
            jugadorActual = (jugadorActual + 1) % 2;
            jugadores[jugadorActual].movidaOtroJugador(ubicacion);
            lock.lock();
            try {
                otroJugadorTurno.signal();
            } finally {
                lock.unlock();
            }
            return true;
        } else {
            jugadorActual = (jugadorActual + 1) % 2;
            jugadores[jugadorActual].movidaOtroJugador(ubicacion);
            lock.lock();
            try {
                otroJugadorTurno.signal();
            } finally {
                lock.unlock();
            }
            return false;
        }
    }

    /**
     *
     * Recibe una ubicacion y el numero de jugador
     * Si la ubicacion tiene un "1" quiere decir esta ubicada y se puede
     * destruir por lo que el valor de la ubicacion se cambia a "0", devuelve un
     * "true"
     * Si la ubicacion tiene un "0" quiere decir que ya habia algo pero
     * se destruyo, devuelve un "false"
     * Si tiene un "" quiere decir que nunca ha habido nada por lo que devuelve
     * un "false"
     * El numero de jugador se utiliza para decidir cual area de juego utilizar
     */
    public boolean estaOcupado(int location, int jugador) {
        boolean salida = false;
        if (jugador == JUGADOR_1) {
            if (areaJuego2[location].equals("1")) {
                salida = true;
                areaJuego2[location] = "0";
                oportunidadesRestantes1 = oportunidadesRestantes1 - 1;
                System.out.println("Servidor: Nave Destruida");
            }
        }
        if (jugador == JUGADOR_2) {
            if (areaJuego1[location].equals("1")) {
                salida = true;
                areaJuego1[location] = "0";
                oportunidadesRestantes2 = oportunidadesRestantes2 - 1;
                System.out.println("Servidor: Nave Destruida");
            }
        }
        System.out.println("Servidor: Jugada Valida");
        return salida;
    }
  #2 (permalink)  
Antiguo 18/04/2009, 21:13
 
Fecha de Ingreso: abril-2009
Mensajes: 3
Antigüedad: 15 años
Puntos: 0
Respuesta: Problema Cliente - Servidor Java

esta es la otra parte del código del servidor, ambas partes van en el mismo archivo
Código:
private class Jugador implements Runnable {

        private Socket conexion;
        private Scanner entrada;
        private Formatter salida;
        private int numerojugador;
        private String turno;
        private boolean enEspera = true;
        private boolean clientesListos;

        public Jugador(Socket socket, int numero, boolean clientesListos) {

            this.clientesListos = clientesListos;
            numerojugador = numero;
            if (clientesListos == true) {
                turno = "Sin Turno";
            } else {
                turno = TURNOS[numerojugador];
            }
            conexion = socket;
            try {
                entrada = new Scanner(conexion.getInputStream());
                salida = new Formatter(conexion.getOutputStream());
            } catch (IOException ex) {
                ex.printStackTrace();
                System.exit(1);
            }
            System.out.println("Servidor: Iniciado Jugador");
            for (int i = 0; i < 15; i++) {
                if (entrada.hasNext()) {
                    int nave = entrada.nextInt();
                    if (nave <= 0) {
                        if (numerojugador == JUGADOR_1) {
                            areaJuego1[Math.abs(nave)] = "1";
                        } else {
                            areaJuego2[Math.abs(nave)] = "1";
                        }
                    }
                }
            }

        }

        public void movidaOtroJugador(int ubicacion) {
            salida.format("Movida Oponente\n");
            salida.format("%d\n", ubicacion);
            salida.flush();
            System.out.println("Servidor: Procesando Jugada Otro jugador");
        }

        public void run() {
            try {
                mostrarMensaje("Jugador " + turno + " Conectado\n");
                salida.format("%s\n", turno);
                salida.flush();
                if ( clientesListos == true) {
                    salida.format("Conexion Rechazada\n");
                    System.out.println("Conexion Rechazada");
                    salida.flush();
                    try {
                        conexion.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                } else {
                    if (numerojugador == JUGADOR_1) {
                        salida.format("%s\n%s", "Juador 1 conectado", "Esperando por el otro jugador\n");
                        salida.flush();
                        lock.lock();
                        try {
                            while (enEspera) {
                                otroJugadorConectado.await();
                            }
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        } finally {
                            lock.unlock();
                        }
                        salida.format("Otro jugador conectado. Su turno.\n");
                        salida.flush();
                    } else {
                        salida.format("Jugador 2 conectado, por favor espere\n");
                        salida.flush();
                    }
                    while (!juegoTerminado()) {
                        int ubicacion = 0;
                        if (entrada.hasNext()) {
                            ubicacion = entrada.nextInt();
                        }
                        if (validarJugada(ubicacion, numerojugador)) {
                            mostrarMensaje("\nUbicacion: " + ubicacion + "\n");
                            salida.format("Jugada Valida.\n");
                            salida.flush();
                            if (oportunidadesRestantes1 - 1 == 0 || oportunidadesRestantes2 - 1 == 0) {
                                salida.format("partida terminada");
                            }
                        } else {
                            salida.format("Jugada Invalida, prueba otra vez\n");
                            salida.flush();
                        }
                    }
                }
            } finally {
                try {
                    conexion.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                    System.exit(1);
                }
            }
        }
        public void setSuspendido(boolean status) {
            enEspera = status;
        }
    }
}
  #3 (permalink)  
Antiguo 18/04/2009, 21:14
 
Fecha de Ingreso: abril-2009
Mensajes: 3
Antigüedad: 15 años
Puntos: 0
Respuesta: Problema Cliente - Servidor Java

y este es el código que estoy usando para el cliente

Código:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Formatter;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Cliente extends JFrame implements Runnable, ActionListener {
    private JTextField jTextField1;
    private JTextField jTextField2;
    private JTextArea jTextArea;
    private JButton boton;
    private String[][] tablero = {{"1", "1", "1", "1", "1", "1", "1", "1", "1"},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "1", "", "1", "1", "1", "1", ""},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", ""},
        {"", "", "", "", "", "", "", "", "1"}};
    private int[] ubicacionNaves;
    private int casillaActual;
    private Socket conexion;
    private Scanner entrada;
    private Formatter salida;
    private String host;
    private String turno;
    private boolean miTurno;
    private final String MARCA_1 = "1"; // mark for first client
    private final String MARCA_2 = "2"; // mark for second client
    public Cliente(String host) {
        super("Cliente");
        this.host = host;
        jTextArea = new JTextArea(4, 30);
        jTextArea.setEditable(false);
        add(new JScrollPane(jTextArea), BorderLayout.CENTER);
        System.out.println("Cliente: Inicializada Area de Texto");
        jTextField1 = new JTextField();
        jTextField1.setEditable(false);
        add(jTextField1, BorderLayout.NORTH);
        System.out.println("Cliente: Inicializada TextField 1");
        jTextField2 = new JTextField();
        jTextField2.setEditable(true);
        jTextField2.addActionListener(this);
        add(jTextField2, BorderLayout.SOUTH);
        System.out.println("Cliente: Inicializada TextField 2");
        ubicacionNaves = new int[15];
        getNaves();
        setSize(300, 225);
        setVisible(true);
        iniciarCliente();
        System.out.println("Cliente: Iniciando Cliente...");
    }
    private void getNaves() {
        int index = 0;
        int ubicacion = 0;
        for (int i = 0; i < tablero.length; i++) {
            for (int y = 0; y < tablero[0].length; y++) {
                if (tablero[i][y].equals("1")){
                    ubicacionNaves[index] = ubicacion;
                    index++;
                }
                ubicacion++;
            }
        }
    }
    public void iniciarCliente() {
        try {
            conexion = new Socket(InetAddress.getByName(host), 12345);
            entrada = new Scanner(conexion.getInputStream());
            salida = new Formatter(conexion.getOutputStream());
            System.out.println("Cliente: Cliente iniciado");

            //Para enviar el tablero, envia un negativo
            for(int i = 0; i<ubicacionNaves.length; i++){
                int temp = ubicacionNaves[i];
                int temp2 = temp * 2;
                salida.format("%d\n", temp-temp2);
                salida.flush();
            }
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        ExecutorService worker = Executors.newFixedThreadPool(1);
        System.out.println("Cliente: Ejecutor Iniciado");
        worker.execute(this);
        System.out.println("Cliente: Hilo Iniciando");
    }
    public void run() {
        turno = entrada.nextLine();
        System.out.println("Cliente: Capturando Turno");

        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {
                        jTextField1.setText("Eres el jugador\"" + turno + "\"");
                        System.out.println("Cliente: Indicando Turno");
                    }
                });
        miTurno = (turno.equals(MARCA_1));
        System.out.println("Cliente: Asignando Turno");
        while (true) {
            if (entrada.hasNextLine()) {
                procesarMensaje(entrada.nextLine());
                System.out.println("Cliente: Capturando Mensajes");
            }
        }
    }
    private void procesarMensaje(String mensaje) {
        if (mensaje.equals("Jugada Valida.")) {
            mostrarMensaje("Jugada Valida, espere.\n");
            System.out.println("Cliente: Procesando Jugada Valida");
        } else if (mensaje.equals("Jugada Invalida, prueba otra vez")) {
            mostrarMensaje(mensaje + "\n");
            miTurno = true;
            System.out.println("Cliente: Procesando Jugada invalida");
        } else if (mensaje.equals("Movida Oponente")) {
            int location = entrada.nextInt();
            entrada.nextLine();
            int row = location / 3;
            int column = location % 3;
            mostrarMensaje(Integer.toString(location));
            mostrarMensaje("Movida del Oponente. Su turno.\n");
            miTurno = true;
            System.out.println("Cliente: Procesando jugada del oponente");
        } else if (mensaje.equals("Conexion Rechazada\n")) {
            JOptionPane.showMessageDialog(rootPane, "Conexion Rechazada desde el Servidor");
        } else {
            mostrarMensaje(mensaje + "\n");
        }
    }
    private void mostrarMensaje(final String mensaje) {
        SwingUtilities.invokeLater(
                new Runnable() {

                    public void run() {
                        jTextArea.append(mensaje);
                        System.out.println("Cliente: Mostrando mensaje");
                    }
                });
    }

    public void enviarJugada(int location) {
        if (miTurno) {
            salida.format("%d\n", location);
            salida.flush();
            miTurno = false;
            System.out.println("Cliente: Enviando Jugada");
        }
    }
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jTextField2) {
            int num = Integer.parseInt(jTextField2.getText());
            enviarJugada(num);
            jTextField2.setText("");
            System.out.println("Cliente: Capturando Evento");
        }
    }
}
tuve que poner todo eso en diferentes mensajes por que eran muchos caracteres, sepan perdonar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 14:08.