Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package controlador;
- //----Imports------------------//
- import java.awt.EventQueue;
- import java.io.DataInputStream;
- import java.io.DataOutputStream;
- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.concurrent.ConcurrentHashMap;
- import javax.swing.DefaultListModel;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JList;
- import javax.swing.JTextArea;
- import javax.swing.SwingConstants;
- /**
- *
- * @author Jesus Dario Rodriguez <http://jdr80.epizy.com/>
- */
- public class Server {
- //---- Declaracion de las variables----------//
- private static final long serialVersionUID = 1L;
- private static Map<String, Socket> allUsersList = new ConcurrentHashMap<>(); // lleva el mapeo de todos los
- // usernames usedos y de sus socket connections
- private static Set<String> activeUserSet = new HashSet<>(); //se lleva el control de todos los usuarios conectados
- private static int port = 8818; // puerto usado
- private JFrame frame; // jframe variable
- private ServerSocket serverSocket; //server socket variable
- private JTextArea serverMessageBoard; // variable for server message board on UI
- private JList allUserNameList; // variable on UI
- private JList activeClientList; // variable on UI
- private DefaultListModel<String> activeDlm = new DefaultListModel<String>(); // keeps list of active users for display on UI
- private DefaultListModel<String> allDlm = new DefaultListModel<String>(); // keeps list of all users for display on UI
- /**
- * Launch the application.
- */
- public static void main(String[] args) { // empiezan las funciones
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- Server window = new Server(); // creacion del objeto
- window.frame.setVisible(true); //jframe visible
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * Creando la aplicacion
- */
- public Server() {
- initialize(); // componentes de swing
- try {
- serverSocket = new ServerSocket(port); // crando soket para el cliente
- serverMessageBoard.append("Server iniciado en el puerto: " + port + "\n"); // imprimiendo mensaje en el tablero
- serverMessageBoard.append("Esperando por clientes...\n");
- new ClientAccept().start(); // creando hilo de cliente
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- class ClientAccept extends Thread {
- @Override
- public void run() {
- while (true) {
- try {
- Socket clientSocket = serverSocket.accept(); // creando el soket para el cliente
- String uName = new DataInputStream(clientSocket.getInputStream()).readUTF();
- DataOutputStream cOutStream = new DataOutputStream(clientSocket.getOutputStream());
- if (activeUserSet != null && activeUserSet.contains(uName)) {
- cOutStream.writeUTF("usuario ya esta registrado");
- } else {
- allUsersList.put(uName, clientSocket); // agregando cliente a la lista de clientes activos
- activeUserSet.add(uName);
- cOutStream.writeUTF(""); // limpiando el mensaje de salida
- activeDlm.addElement(uName); // agregando el usuario a la lista de clientes
- if (!allDlm.contains(uName)) //
- {
- allDlm.addElement(uName);
- }
- activeClientList.setModel(activeDlm); // mostrando los clientes activos en la JList
- allUserNameList.setModel(allDlm);
- serverMessageBoard.append("Cliente " + uName + " Conectado...\n"); // notificando de cliente conectado
- new MsgRead(clientSocket, uName).start(); // crea hilo para leer los mensajes
- new PrepareCLientList().start(); //crea hilo para actualizar los usuarios activos
- }
- } catch (IOException ioex) {
- ioex.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- class MsgRead extends Thread { // este hilo lee los mensajes del los clientes
- Socket s;
- String Id;
- private MsgRead(Socket s, String uname) { // socket y username seran enviados por el cliente
- this.s = s;
- this.Id = uname;
- }
- @Override
- public void run() {
- while (allUserNameList != null && !allUsersList.isEmpty()) { // si la lista de todos los clientes no esta vacia prosigue
- try {
- String message = new DataInputStream(s.getInputStream()).readUTF(); // lee mensaje del cliente
- System.out.println("message read ==> " + message); // imprime mensaje para prueba
- String[] msgList = message.split(":");
- if (msgList[0].equalsIgnoreCase("multicast")) { // si la accione es multicast entonces enviar mensaje a todos los clientes seleccionados activos
- String[] sendToList = msgList[1].split(","); //esta variabel contiene la lista de todos los clientes que recibiran el mensaje
- for (String usr : sendToList) { // para cada usaurio enviar el mensaje
- try {
- if (activeUserSet.contains(usr)) { // checa de nuevo si el cliente sigue activo y despues de checar envia el mensaje
- new DataOutputStream(((Socket) allUsersList.get(usr)).getOutputStream())
- .writeUTF("< " + Id + " >" + msgList[2]); // pone el mensaje en el output stream
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } else if (msgList[0].equalsIgnoreCase("broadcast")) { // si se selecciona multicast, envia el mensaje a tosos los usuarios
- Iterator<String> itr1 = allUsersList.keySet().iterator(); // iterador para los usaurios
- while (itr1.hasNext()) {
- String usrName = (String) itr1.next(); // checa por el username
- if (!usrName.equalsIgnoreCase(Id)) { // chequeo para no autoenviarnos el mensaje
- try {
- if (activeUserSet.contains(usrName)) {
- new DataOutputStream(((Socket) allUsersList.get(usrName)).getOutputStream())
- .writeUTF("< " + Id + " >" + msgList[1]);
- } else {
- // si el usuario no recibio el mensaje entonces notifica al enviador de la desconexion del cliente
- new DataOutputStream(s.getOutputStream())
- .writeUTF("Mensaje no fue enviado a " + usrName + " por que se desconecto.\n");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- } else if (msgList[0].equalsIgnoreCase("Salir")) { // si el porceso de un cliente es terminado notifica a los demas clientes
- activeUserSet.remove(Id); // remueve el usaurio de la lista de clientes activos
- serverMessageBoard.append(Id + " Desconectado....\n");
- new PrepareCLientList().start(); // actualiza la lista de usuarios activos
- Iterator<String> itr = activeUserSet.iterator();
- while (itr.hasNext()) {
- String usrName2 = (String) itr.next();
- if (!usrName2.equalsIgnoreCase(Id)) { //previene enviarnos mensajes a nosotros mismos
- try {
- new DataOutputStream(((Socket) allUsersList.get(usrName2)).getOutputStream())
- .writeUTF(Id + " Desconectado..."); // notifica de la desconexion de un cliente
- } catch (Exception e) {
- e.printStackTrace();
- }
- new PrepareCLientList().start(); // actualiza la lista de clientes desconectados a cada cliente
- }
- }
- activeDlm.removeElement(Id); // remueve la Jlist del server
- activeClientList.setModel(activeDlm); //actualiza la lista de usuarios activos
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- class PrepareCLientList extends Thread { // prepara la lista de usuarios activos que se desplehara en la UI
- @Override
- public void run() {
- try {
- String ids = "";
- Iterator itr = activeUserSet.iterator();
- while (itr.hasNext()) { // prepara el string de cada usuario
- String key = (String) itr.next();
- ids += key + ",";
- }
- if (ids.length() != 0) {
- ids = ids.substring(0, ids.length() - 1);
- }
- itr = activeUserSet.iterator();
- while (itr.hasNext()) { //itera para chacar los usaurios activos
- String key = (String) itr.next();
- try {
- new DataOutputStream(((Socket) allUsersList.get(key)).getOutputStream())
- .writeUTF(":;.,/=" + ids); // setea el output stream cy envia la lista de usaurios activos
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * inicializa los componentes del JFrame.
- */
- private void initialize() {
- frame = new JFrame();
- frame.setBounds(100, 100, 796, 530);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.getContentPane().setLayout(null);
- frame.setTitle("Servidor");
- serverMessageBoard = new JTextArea();
- serverMessageBoard.setEditable(false);
- serverMessageBoard.setBounds(12, 29, 489, 435);
- frame.getContentPane().add(serverMessageBoard);
- serverMessageBoard.setText("Iniciando el server...\n");
- allUserNameList = new JList();
- allUserNameList.setBounds(526, 324, 218, 140);
- frame.getContentPane().add(allUserNameList);
- activeClientList = new JList();
- activeClientList.setBounds(526, 78, 218, 156);
- frame.getContentPane().add(activeClientList);
- JLabel lblNewLabel = new JLabel("todos los usuarios");
- lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
- lblNewLabel.setBounds(530, 295, 127, 16);
- frame.getContentPane().add(lblNewLabel);
- JLabel lblNewLabel_1 = new JLabel("Usuarios Activos");
- lblNewLabel_1.setBounds(526, 53, 98, 23);
- frame.getContentPane().add(lblNewLabel_1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement