Ver Mensaje Individual
  #2 (permalink)  
Antiguo 27/02/2014, 13:26
jcastro3
 
Fecha de Ingreso: marzo-2013
Mensajes: 51
Antigüedad: 12 años
Puntos: 2
Respuesta: Comprobar si dos clientes tienen el mismo nick

La clase Hilo

Código Java:
Ver original
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.PrintWriter;
  5. import java.net.Socket;
  6.  
  7. public class Hilo extends Thread {
  8.    
  9.     //Se establece el socket y nick
  10.     private Socket clientSocket = null;
  11.     private String nick = null;
  12.    
  13.     //Se crea el constructor
  14.     public Hilo(Socket param){
  15.  
  16.         this.clientSocket = param;
  17.  
  18.     }
  19.    
  20.     //Metodo run necesario por el hilo
  21.     public void run(){
  22.  
  23.         try {
  24.            
  25.             //Aqui el cliente conecta con el servidor
  26.             PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
  27.             BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  28.             out.println("Conectando con el servidor.....");
  29.             out.println("Conectado");
  30.            
  31.             //Cuando se conecta un cliente el servidor manda un mensaje al resto de clientes
  32.             //diciendo quien se ha conectado
  33.             this.nick = in.readLine();
  34.             Servidor.comunicar_a_todos("Se ha conectado: " + this.nick, this.nick, 1);
  35.  
  36.             //Se envia el mensaje al resto de clientes
  37.             while(true){
  38.  
  39.                 String mensaje = in.readLine();
  40.                
  41.                 //Si el mensaje es FIN se envia un mensaje a todos diciendo quien se ha desconectado
  42.                 if(mensaje.equals("FIN")){
  43.                     Servidor.comunicar_a_todos("Se ha desconectado: " + this.nick, this.nick, 2);
  44.                     out.println("FIN");
  45.                     break;
  46.                 }
  47.  
  48.                 Servidor.comunicar_a_todos(mensaje,this.nick, 3);
  49.  
  50.             }
  51.  
  52.             Servidor.eliminar_socket_cliente(this.clientSocket);
  53.             clientSocket.close();
  54.  
  55.  
  56.         } catch (IOException e) {
  57.             // TODO Auto-generated catch block
  58.             e.printStackTrace();
  59.         }
  60.  
  61.     }
  62.  
  63. }//Fin clase.

Y la clase servidor

Código Java:
Ver original
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import java.net.ServerSocket;
  4. import java.net.Socket;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import javax.swing.JOptionPane;
  8.  
  9. public class Servidor {
  10.  
  11.     /**
  12.      * @param args
  13.      */
  14.    
  15.     //Creo un ArrayList de Sockets (no sabia como hacerlo con un array)
  16.     private static ArrayList<Socket> listadoClientes = new ArrayList<Socket>();
  17.  
  18.     //Creo un ArrayList de usuarios conectados. Este lo he creado para sacar la lista de
  19.     //usuarios conectados pero no lo he conseguido al final. Por tanto por aqui hay codigo
  20.     //que sobra.
  21.     private static ArrayList<String> listadoConectados = new ArrayList<String>();
  22.  
  23.     private static String cadena_usuariosConectados = "";
  24.  
  25.     public static void main(String[] args) {
  26.         // TODO Auto-generated method stub
  27.  
  28.         //Delcaro el puerto que usa el servidor
  29.         String puerto= "7777";
  30.         try {
  31.             //Instancio el serverSocket
  32.             ServerSocket serverSocket = new ServerSocket(Integer.parseInt(puerto));
  33.  
  34.             while(true){
  35.                 //Lo meto en un bucle infinito para que siempre este escuchando
  36.                 //y aceptando peticiones de clientes
  37.                 Socket cliente = serverSocket.accept();
  38.                 new Hilo(cliente).start();
  39.                 //Cuando se conecta un cliente le añado a la lista
  40.                 listadoClientes.add(cliente);
  41.  
  42.             }
  43.  
  44.         } catch (IOException e) {
  45.             // TODO Auto-generated catch block
  46.             e.printStackTrace();
  47.         }
  48.  
  49.     }
  50.     //Creo este metodo sincronizado para que los mensajes lleguen a la vez a los clientes
  51.     public static synchronized void comunicar_a_todos(String mensaje, String nick, int tipo){
  52.  
  53.         //El servidor comunica a todos los clientes conectados los nicks que van conectando
  54.         //y los nicks que se van desconectando y los mensajes que escribe cada uno.
  55.  
  56.         Socket s = null;
  57.         PrintWriter p;
  58.        
  59.         //Al ser listadoClientes un arrayList tenemos que recorrerlo con un iterador
  60.         Iterator<Socket> itr = listadoClientes.iterator();
  61.        
  62.         //Definimos un tipo para saber si un cliente se conecta o se desconecta
  63.         if(tipo == 1){
  64.            
  65.                     listadoConectados.add(nick);
  66.                 cadena_lista_conectados();
  67.                
  68.            
  69.                
  70.         }
  71.  
  72.         if(tipo == 2){
  73.             listadoConectados.remove(nick);
  74.             cadena_lista_conectados();
  75.         }
  76.  
  77.         while(itr.hasNext()) {
  78.             s = itr.next();
  79.             try {
  80.                 p = new PrintWriter(s.getOutputStream(),true);
  81.                 if(tipo == 1){ //Se conecta un nuevo cliente
  82.                     p.println(mensaje); //Pinta: Se ha conectado: ...              
  83.                 }else if(tipo == 2){ //Se desconecta un cliente
  84.                     p.println(mensaje); //Pinta: Se ha desconectado: ...
  85.                 }else{// Intercambio de mensajes
  86.                     p.println(nick + ">" + mensaje);
  87.                 }
  88.             } catch (IOException e) {
  89.                 // TODO Auto-generated catch block
  90.                 e.printStackTrace();
  91.             }
  92.  
  93.         }
  94.         cadena_usuariosConectados = "";
  95.     }
  96.  
  97.  
  98.     private static void cadena_lista_conectados(){
  99.         //Transforma el ArrayList de usuarios conectados a cadena para enviar por el socket
  100.        
  101.         for(String s:listadoConectados){
  102.            
  103.             cadena_usuariosConectados += s + "\n";
  104.         }
  105.  
  106.     }
  107.  
  108.     public static synchronized void eliminar_socket_cliente(Socket cliente){
  109.  
  110.         Iterator<Socket> itr = listadoClientes.iterator();
  111.  
  112.         while(itr.hasNext()){
  113.  
  114.             Socket soc = itr.next();
  115.  
  116.             if(soc.equals(cliente)){
  117.                 itr.remove();
  118.                 break;
  119.             }
  120.         }
  121.     }
  122.  
  123. }