Threads en servidor de mensajes instantáneos.

Reply

Join Date: Nov 2009
Posts: 5
Reputation: eleal is an unknown quantity at this point 
Solved Threads: 0
eleal eleal is offline Offline
Newbie Poster

Threads en servidor de mensajes instantáneos.

 
0
  #1
15 Days Ago
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:
  1. public class Servidor {
  2. public static void main(String[] args) throws IOException {
  3. ServerSocket serverSocket = null;
  4. boolean listening = true;
  5. new StdinReaderThread();
  6.  
  7. try {
  8. serverSocket = new ServerSocket(4444);
  9. } catch (IOException e) {
  10. System.err.println("No pudo crearse el socket");
  11. System.exit(-1);
  12. }
  13.  
  14. while (listening){
  15. new HiloServidor(serverSocket.accept()).start();
  16. }
  17. serverSocket.close();
  18. }
  19. }

y el hilo que lee del teclado:
  1. public class StdinReaderThread implements Runnable{
  2. BufferedReader stdin;
  3.  
  4. public StdinReaderThread(){
  5. Thread subpr = new Thread(this,"x");
  6. stdin = new BufferedReader( new InputStreamReader(System.in));
  7. subpr.start();
  8. }
  9. public void run(){
  10. while (true){
  11. try{
  12. String stdinline = stdin.readLine();
  13. if( stdinline.startsWith("q")){
  14. System.out.println("salir");
  15. }
  16. else if( stdinline.startsWith("m"))
  17. System.out.println("enviar mensaje");
  18. else if( stdinline.startsWith("l"))
  19. System.out.println("enviar login");
  20. else if( stdinline.startsWith("u"))
  21. System.out.println("lista usuarios");
  22. } catch (Exception e){}
  23. }
  24. }
  25. }

Saludos,
Last edited by eleal; 15 Days Ago at 11:08 am.
Reply With Quote Quick reply to this message  
Reply

Message:



Similar Threads
Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC