Server allows to work concurrently with several clients

0

I have created the server class, but I am not able to make clients work concurrently with several clients, I have seen tutorials and I am not able to modify my code so that this can be done.

Can you help me please? Thank you very much, I leave you my code here.

import java.net.*;
import java.io.*;

public class Servidor {

    public static void main(String[] args) throws IOException {

        int nSecreto = generar_nSecreto();
        int nJugador = 0;
        boolean adivinado = false;

        System.out.println("Número secreto generado al azar en el servidor: " + nSecreto);

        ServerSocket sServidor = null;
        Socket sCliente = null;

        System.out.println("Servidor OK...\n Esperando jugadores...");

        try {

            sServidor = new ServerSocket(1500);
            sCliente = sServidor.accept();
            System.out.println("Se ha conectado en el servidor");

            DataInputStream entrada = new DataInputStream(new BufferedInputStream(sCliente.getInputStream()));
            DataOutputStream salida = new DataOutputStream(new BufferedOutputStream(sCliente.getOutputStream()));

            while (true) {
                if (!adivinado) {
                    nJugador = entrada.readInt();

                    if (nJugador == nSecreto) {
                        adivinado = true;
                        salida.writeBoolean(true);
                    } else if (nJugador > nSecreto) {
                        salida.writeBoolean(false);
                        salida.writeUTF("\n[INCORRECTO]: El número es menor que " + nJugador + "\n");
                    } else if (nJugador < nSecreto) {
                        salida.writeBoolean(false);
                        salida.writeUTF("\n[INCORRECTO]: El número es mayor que " + nJugador + "\n");
                    }
                } else if (adivinado) {
                    salida.writeUTF("\nHas acertado el número secreto [ " + nJugador + " ] ¡Enorabuena!\n");
                } else {
                    sServidor.close();
                    sCliente.close();
                }
            }
        } catch (IOException e) {
            System.out.println("\nError al intentar escuchar por el puerto 1500 o la conexión con el jugador\n");
            System.out.println(e.getMessage());
        }
    }

    private static int generar_nSecreto() {
        return (int) (Math.random() * 150 + 0);
    }
}
    
asked by Juan Martinez 11.05.2018 в 04:09
source

1 answer

0

There are a couple of things that I'm not clear about how customers and the server should behave in case of failure and correct answers, but in principle, what you should do is that each client runs in a Thread separated to prevent the server from being blocked. The code would look something like this:

private static class Jugador extends Thread {
    private Socket socket;
    private int nSecreto;
    private boolean adivinado = false;

    public Jugador(Socket socket, int nSecreto) {
        this.socket = socket;
        this.nSecreto = nSecreto;
    }

    public void run() {
        try {
            DataInputStream entrada = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
            DataOutputStream salida = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));

            int nJugador = entrada.readInt();

            if (!adivinado) {
                if (nJugador == nSecreto) {
                    adivinado = true;
                    salida.writeBoolean(true);
                } else if (nJugador > nSecreto) {
                    salida.writeBoolean(false);
                    salida.writeUTF("\n[INCORRECTO]: El número es menor que " + nJugador + "\n");
                } else if (nJugador < nSecreto) {
                    salida.writeBoolean(false);
                    salida.writeUTF("\n[INCORRECTO]: El número es mayor que " + nJugador + "\n");
                }
            } else if (adivinado) {
                salida.writeUTF("\nHas acertado el número secreto [ " + nJugador + " ] ¡Enorabuena!\n");
            } else {
                //Este juego de if/else if/else es lo que no entiendo, pero no importa de cara a lo que estás preguntando
                //socket.close();
            }

        } catch (IOException e) {
            //Log de excepcion
        }
    }
}

public static void main(String[] args) throws IOException {

    int nSecreto = generar_nSecreto();

    System.out.println("Número secreto generado al azar en el servidor: " + nSecreto);

    ServerSocket sServidor = null;

    System.out.println("Servidor OK...\n Esperando jugadores...");

    try {

        sServidor = new ServerSocket(1500);
        System.out.println("Se ha conectado en el servidor");

        while (true) {
            Jugador tJugador = new Jugador(sServidor.accept(), nSecreto);
            tJugador.start();
        }
    } catch (IOException e) {
        System.out.println("\nError al intentar escuchar por el puerto 1500 o la conexión con el jugador\n");
        System.out.println(e.getMessage());
    }
}
    
answered by 11.05.2018 / 08:01
source