Advertisement
Metziop

Untitled

Jun 8th, 2021
1,081
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.04 KB | None | 0 0
  1. package controlador;
  2. //----Imports------------------//
  3.  
  4. import java.awt.EventQueue;
  5. import java.io.DataInputStream;
  6. import java.io.DataOutputStream;
  7. import java.io.IOException;
  8. import java.net.ServerSocket;
  9. import java.net.Socket;
  10. import java.util.HashSet;
  11. import java.util.Iterator;
  12. import java.util.Map;
  13. import java.util.Set;
  14. import java.util.concurrent.ConcurrentHashMap;
  15. import javax.swing.DefaultListModel;
  16. import javax.swing.JFrame;
  17. import javax.swing.JLabel;
  18. import javax.swing.JList;
  19. import javax.swing.JTextArea;
  20. import javax.swing.SwingConstants;
  21.  
  22. /**
  23.  *
  24.  * @author Jesus Dario Rodriguez <http://jdr80.epizy.com/>
  25.  */
  26. public class Server {
  27. //---- Declaracion de las variables----------//
  28.  
  29.     private static final long serialVersionUID = 1L;
  30.     private static Map<String, Socket> allUsersList = new ConcurrentHashMap<>(); // lleva el mapeo de todos los
  31.     // usernames usedos y de sus socket connections
  32.     private static Set<String> activeUserSet = new HashSet<>(); //se lleva el control de todos los usuarios conectados
  33.  
  34.     private static int port = 8818;  // puerto usado
  35.  
  36.     private JFrame frame; // jframe variable
  37.  
  38.     private ServerSocket serverSocket; //server socket variable
  39.  
  40.     private JTextArea serverMessageBoard; // variable for server message board on UI
  41.  
  42.     private JList allUserNameList;  // variable on UI
  43.  
  44.     private JList activeClientList; // variable on UI
  45.  
  46.     private DefaultListModel<String> activeDlm = new DefaultListModel<String>(); // keeps list of active users for display on UI
  47.  
  48.     private DefaultListModel<String> allDlm = new DefaultListModel<String>(); // keeps list of all users for display on UI
  49.  
  50.     /**
  51.      * Launch the application.
  52.      */
  53.     public static void main(String[] args) {  // empiezan las funciones
  54.         EventQueue.invokeLater(new Runnable() {
  55.             public void run() {
  56.                 try {
  57.                     Server window = new Server();  // creacion del objeto
  58.                     window.frame.setVisible(true); //jframe visible
  59.                 } catch (Exception e) {
  60.                     e.printStackTrace();
  61.                 }
  62.             }
  63.         });
  64.     }
  65.  
  66.     /**
  67.      * Creando la aplicacion
  68.      */
  69.     public Server() {
  70.         initialize();  // componentes de swing
  71.         try {
  72.             serverSocket = new ServerSocket(port);  // crando soket para el cliente
  73.             serverMessageBoard.append("Server iniciado en el puerto: " + port + "\n"); // imprimiendo mensaje en el tablero
  74.             serverMessageBoard.append("Esperando por clientes...\n");
  75.             new ClientAccept().start(); // creando hilo de cliente
  76.         } catch (Exception e) {
  77.             e.printStackTrace();
  78.         }
  79.     }
  80.  
  81.     class ClientAccept extends Thread {
  82.  
  83.         @Override
  84.         public void run() {
  85.             while (true) {
  86.                 try {
  87.                     Socket clientSocket = serverSocket.accept();  // creando el soket para el cliente
  88.                     String uName = new DataInputStream(clientSocket.getInputStream()).readUTF();
  89.                     DataOutputStream cOutStream = new DataOutputStream(clientSocket.getOutputStream());
  90.                     if (activeUserSet != null && activeUserSet.contains(uName)) {
  91.                         cOutStream.writeUTF("usuario ya esta registrado");
  92.                     } else {
  93.                         allUsersList.put(uName, clientSocket); // agregando cliente a la lista de clientes activos
  94.                         activeUserSet.add(uName);
  95.                         cOutStream.writeUTF(""); // limpiando el mensaje de salida
  96.                         activeDlm.addElement(uName); // agregando el usuario a la lista de clientes
  97.                         if (!allDlm.contains(uName)) //
  98.                         {
  99.                             allDlm.addElement(uName);
  100.                         }
  101.                         activeClientList.setModel(activeDlm); // mostrando los clientes activos en la JList
  102.                         allUserNameList.setModel(allDlm);
  103.                         serverMessageBoard.append("Cliente " + uName + " Conectado...\n"); // notificando de cliente conectado
  104.                         new MsgRead(clientSocket, uName).start(); // crea hilo para leer los mensajes
  105.                         new PrepareCLientList().start(); //crea hilo para actualizar los usuarios activos
  106.                     }
  107.                 } catch (IOException ioex) {  
  108.                     ioex.printStackTrace();
  109.                 } catch (Exception e) {
  110.                     e.printStackTrace();
  111.                 }
  112.             }
  113.         }
  114.     }
  115.  
  116.     class MsgRead extends Thread { // este hilo lee los mensajes del los clientes
  117.  
  118.         Socket s;
  119.         String Id;
  120.  
  121.         private MsgRead(Socket s, String uname) { // socket y username seran enviados por el cliente
  122.             this.s = s;
  123.             this.Id = uname;
  124.         }
  125.  
  126.         @Override
  127.         public void run() {
  128.             while (allUserNameList != null && !allUsersList.isEmpty()) {  // si la lista de todos los clientes no esta vacia prosigue
  129.                 try {
  130.                     String message = new DataInputStream(s.getInputStream()).readUTF(); // lee mensaje del cliente
  131.                     System.out.println("message read ==> " + message); // imprime mensaje para prueba
  132.                     String[] msgList = message.split(":");
  133.                    
  134.                     if (msgList[0].equalsIgnoreCase("multicast")) { // si la accione es  multicast entonces enviar mensaje a todos los clientes seleccionados activos
  135.                         String[] sendToList = msgList[1].split(","); //esta variabel contiene la lista de todos los clientes que recibiran el mensaje
  136.                         for (String usr : sendToList) { // para cada usaurio enviar el mensaje
  137.                             try {
  138.                                 if (activeUserSet.contains(usr)) { // checa de nuevo si el cliente sigue activo y despues de checar envia el mensaje
  139.                                     new DataOutputStream(((Socket) allUsersList.get(usr)).getOutputStream())
  140.                                             .writeUTF("< " + Id + " >" + msgList[2]); // pone el mensaje en el output stream
  141.                                 }
  142.                             } catch (Exception e) {
  143.                                 e.printStackTrace();
  144.                             }
  145.                         }
  146.                     } else if (msgList[0].equalsIgnoreCase("broadcast")) { // si se selecciona multicast, envia el mensaje a tosos los usuarios
  147.  
  148.                         Iterator<String> itr1 = allUsersList.keySet().iterator(); // iterador para los usaurios
  149.                         while (itr1.hasNext()) {
  150.                             String usrName = (String) itr1.next(); // checa por el username
  151.                             if (!usrName.equalsIgnoreCase(Id)) { // chequeo para no autoenviarnos el mensaje
  152.                                 try {
  153.                                     if (activeUserSet.contains(usrName)) {
  154.                                         new DataOutputStream(((Socket) allUsersList.get(usrName)).getOutputStream())
  155.                                                 .writeUTF("< " + Id + " >" + msgList[1]);
  156.                                     } else {
  157.                                         // si el usuario no recibio el mensaje entonces notifica al enviador de la desconexion del cliente
  158.                                         new DataOutputStream(s.getOutputStream())
  159.                                                 .writeUTF("Mensaje no fue enviado a " + usrName + " por que se desconecto.\n");
  160.                                     }
  161.                                 } catch (Exception e) {
  162.                                     e.printStackTrace();
  163.                                 }
  164.                             }
  165.                         }
  166.                     } else if (msgList[0].equalsIgnoreCase("Salir")) { // si el porceso de un cliente es terminado notifica a los demas clientes
  167.                         activeUserSet.remove(Id); // remueve el usaurio de la lista de clientes activos
  168.                         serverMessageBoard.append(Id + " Desconectado....\n");
  169.  
  170.                         new PrepareCLientList().start(); // actualiza la lista de usuarios activos
  171.  
  172.                         Iterator<String> itr = activeUserSet.iterator();
  173.                         while (itr.hasNext()) {
  174.                             String usrName2 = (String) itr.next();
  175.                             if (!usrName2.equalsIgnoreCase(Id)) { //previene enviarnos mensajes a nosotros mismos
  176.                                 try {
  177.                                     new DataOutputStream(((Socket) allUsersList.get(usrName2)).getOutputStream())
  178.                                             .writeUTF(Id + " Desconectado..."); // notifica de la desconexion de un cliente
  179.                                 } catch (Exception e) {
  180.                                     e.printStackTrace();
  181.                                 }
  182.                                 new PrepareCLientList().start(); // actualiza la lista de clientes desconectados a cada cliente
  183.                             }
  184.                         }
  185.                         activeDlm.removeElement(Id); // remueve la Jlist del server
  186.                         activeClientList.setModel(activeDlm); //actualiza la lista de usuarios activos
  187.                     }
  188.                 } catch (Exception e) {
  189.                     e.printStackTrace();
  190.                 }
  191.             }
  192.         }
  193.     }
  194.  
  195.     class PrepareCLientList extends Thread { // prepara la lista de usuarios activos que se desplehara en la UI
  196.  
  197.         @Override
  198.         public void run() {
  199.             try {
  200.                 String ids = "";
  201.                 Iterator itr = activeUserSet.iterator();
  202.                 while (itr.hasNext()) { // prepara el string de cada usuario
  203.                     String key = (String) itr.next();
  204.                     ids += key + ",";
  205.                 }
  206.                 if (ids.length() != 0) {
  207.                     ids = ids.substring(0, ids.length() - 1);
  208.                 }
  209.                 itr = activeUserSet.iterator();
  210.                 while (itr.hasNext()) { //itera para chacar los usaurios activos
  211.                     String key = (String) itr.next();
  212.                     try {
  213.                         new DataOutputStream(((Socket) allUsersList.get(key)).getOutputStream())
  214.                                 .writeUTF(":;.,/=" + ids); // setea el output stream cy envia la lista de usaurios activos
  215.                     } catch (Exception e) {
  216.                         e.printStackTrace();
  217.                     }
  218.                 }
  219.             } catch (Exception e) {
  220.                 e.printStackTrace();
  221.             }
  222.         }
  223.     }
  224.  
  225.     /**
  226.      * inicializa los componentes del JFrame.
  227.      */
  228.     private void initialize() {
  229.         frame = new JFrame();
  230.         frame.setBounds(100, 100, 796, 530);
  231.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  232.         frame.getContentPane().setLayout(null);
  233.         frame.setTitle("Servidor");
  234.  
  235.         serverMessageBoard = new JTextArea();
  236.         serverMessageBoard.setEditable(false);
  237.         serverMessageBoard.setBounds(12, 29, 489, 435);
  238.         frame.getContentPane().add(serverMessageBoard);
  239.         serverMessageBoard.setText("Iniciando el server...\n");
  240.  
  241.         allUserNameList = new JList();
  242.         allUserNameList.setBounds(526, 324, 218, 140);
  243.         frame.getContentPane().add(allUserNameList);
  244.  
  245.         activeClientList = new JList();
  246.         activeClientList.setBounds(526, 78, 218, 156);
  247.         frame.getContentPane().add(activeClientList);
  248.  
  249.         JLabel lblNewLabel = new JLabel("todos los usuarios");
  250.         lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
  251.         lblNewLabel.setBounds(530, 295, 127, 16);
  252.         frame.getContentPane().add(lblNewLabel);
  253.  
  254.         JLabel lblNewLabel_1 = new JLabel("Usuarios Activos");
  255.         lblNewLabel_1.setBounds(526, 53, 98, 23);
  256.         frame.getContentPane().add(lblNewLabel_1);
  257.  
  258.     }
  259. }
  260.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement