eleal 0 Newbie Poster

Hola a todos,

Estoy tratando de escribir un servidor de mensajería entre clientes, en Java. El problema que tengo es cuando quiero terminar el servidor. El servidor que he pensado funciona así: Cada cliente se conecta a un hilo que crea el servidor y allí envía los mensajes. El problema está en cómo hacer que cuando administrador del servidor desee terminar el programa (presionando 'q' en el teclado), éste acabe con todos los hilos que ha creado y cierre. Para ello había pensado lo siguiente: Que el programa servidor prinicipal, antes de crear cualquier thread para atender a los usuarios, cree un hilo especial dedicado a leer de la entrada por teclado, pero ¿cómo le avisa éste al proceso principal que debe terminar y que por tanto el proceso principal debe decir a todos los demás hilos que ha creado que terminen?

El código que llevo es:

Servidor:

public class Servidor {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        boolean listening = true;
		new StdinReaderThread();

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("No pudo crearse el socket");
            System.exit(-1);
        }

        while (listening){
        	new HiloServidor(serverSocket.accept()).start();
		}
        serverSocket.close();
    }
}

y el hilo que lee del teclado:

public class StdinReaderThread implements Runnable{
		BufferedReader stdin;

		public StdinReaderThread(){
			Thread subpr = new Thread(this,"x");
			stdin = new BufferedReader( new InputStreamReader(System.in));
			subpr.start();
		}
		public void run(){
			while (true){
			   try{
			      String stdinline = stdin.readLine();
			      if( stdinline.startsWith("q")){
				    System.out.println("salir");
			       }
				  else if( stdinline.startsWith("m"))
					System.out.println("enviar mensaje");
				  else if( stdinline.startsWith("l"))
					System.out.println("enviar login");
				  else if( stdinline.startsWith("u"))
					System.out.println("lista usuarios");
			    } catch (Exception e){}
		    }
        }
}

Saludos,

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.