elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Ejercicios
| | | |-+  Cómo enviar un ArrayList del cliente al servidor usando UDP?
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Cómo enviar un ArrayList del cliente al servidor usando UDP?  (Leído 4,320 veces)
novato991

Desconectado Desconectado

Mensajes: 4


Ver Perfil
Cómo enviar un ArrayList del cliente al servidor usando UDP?
« en: 27 Mayo 2019, 15:58 pm »

Quiero enviar una lista de números al servidor para que este al leerlos efectúe las operaciones correspondientes y devuelva el resultado de las mismas al cliente. Luego volverá a pedir números al cliente y de nuevo le devolverá el resultado correspondiente, repitiéndose el proceso hasta que el cliente introduzca un *, entonces ahí se cerraría conexión con el servidor. Tengo que hacerlo obligatoriamente utilizando protocolo UDP.

El problema es que al mandar los números por lo visto al servidor no le llegan dichos números y no hace nada. Cuando ejecuto el programa me pide los 4 números, los introduzco y ahí es donde se queda parado, el servidor no devuelve ningún resultado. Para guardar los números he utilizado el ArrayList numeros... el problema es el proceso para empaquetar esa lista de números en bytes, mandarlo al servidor y que este lo decodifique y lea esos números, ahí por lo visto no le llega la información al servidor. Soy un novato en esto de conexiones TCP/UDP, seguro que me habré equivocado pero no sé como solucionarlo, espero podáis orientarme un poco, porque estoy más perdido que un pulpo en un garaje.

Dejo los códigos de Servidor y Cliente, a ver si podéis decirme dónde he fallado...

Código
  1.    import java.awt.List;
  2.    import java.io.ByteArrayInputStream;
  3.    import java.io.ObjectInputStream;
  4.    import java.net.DatagramPacket;
  5.    import java.net.DatagramSocket;
  6.    import java.net.InetAddress;
  7.    import java.util.ArrayList;
  8.  
  9.    public class Servidor {
  10.  
  11.        public static void main(String args[]) throws Exception {
  12.  
  13.            DatagramSocket serverSocket = new DatagramSocket(9886);
  14.            byte[] infoRecibida = new byte[1024];
  15.            byte[] infoEnviada = new byte[1024];
  16.            byte[] paquete = new byte[1024];
  17.            String cadena;
  18.            List list;
  19.            int n1,n2,n3,n4;
  20.            int res;
  21.            String num;
  22.            String num1,num2,num3,num4;
  23.            String x;
  24.  
  25.  
  26.            while (true) {
  27.  
  28.                System.out.println("Esperando datagrama...");            
  29.                infoRecibida = new byte[1024];
  30.                DatagramPacket paqRecibido = new DatagramPacket(infoRecibida, infoRecibida.length);
  31.                serverSocket.receive(paqRecibido);            
  32.  
  33.  
  34.             // IP y puerto desde donde se manda mensaje
  35.  
  36.                InetAddress IPOrigen = paqRecibido.getAddress();
  37.                int puerto = paqRecibido.getPort();
  38.  
  39.  
  40.                //Estas dos lineas supuestamente serían para poder leer el arraylist enviado desde el cliente, aunque igual estoy equivocado
  41.  
  42.                ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(infoRecibida));
  43.                ArrayList<Integer> numeros = (ArrayList<Integer>)inputStream.readObject();
  44.  
  45.                n1 = numeros.get(0);
  46.                n2 = numeros.get(1);
  47.                n3 = numeros.get(2);
  48.                n4 = numeros.get(3);
  49.  
  50.                num1= Integer.toString(n1);
  51.                num2= Integer.toString(n2);
  52.                num3= Integer.toString(n3);
  53.                num4= Integer.toString(n4);
  54.  
  55.  
  56.                // Si alguno de los números introducidos es *
  57.                // envío "x" al cliente para que este se cierre, posteriormente sale del bucle y se cierra también el servidor
  58.  
  59.                if (num1=="*"||num2=="*"||num3=="*"||num4=="*") {
  60.                 x = "x";
  61.                 paquete = x.getBytes();
  62.                 DatagramPacket paqueteFinal = new DatagramPacket(paquete, paquete.length, IPOrigen, puerto);
  63.                    break;
  64.                }
  65.  
  66.  
  67.                //Hago las operaciones, el resultado lo paso a cadena y luego a bytes, para ser enviado al cliente
  68.  
  69.                res=(n1+n2)*n3-n4;
  70.                num = Integer.toString(res);                      
  71.                infoEnviada=num.getBytes();
  72.  
  73.  
  74.  
  75.                // ENVIO DATAGRAMA AL CLIENTE
  76.  
  77.                DatagramPacket paqEnviado = new DatagramPacket(infoEnviada, infoEnviada.length, IPOrigen, puerto);
  78.                serverSocket.send(paqEnviado);
  79.  
  80.            } //Fin While
  81.  
  82.  
  83.            serverSocket.close();
  84.            System.out.println("Socket cerrado...");
  85.  
  86.        }
  87.  
  88.    }
  89.  
  90.  
  91.  

Código
  1.  
  2.    import java.io.BufferedReader;
  3.    import java.io.ByteArrayOutputStream;
  4.    import java.io.InputStreamReader;
  5.    import java.io.ObjectOutputStream;
  6.    import java.net.DatagramPacket;
  7.    import java.net.DatagramSocket;
  8.    import java.net.InetAddress;
  9.    import java.util.ArrayList;
  10.  
  11.    public class Cliente {
  12.  
  13.        public static void main(String[] args) throws Exception {
  14.  
  15.         String cadena;    
  16.         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));                
  17.         DatagramSocket clientSocket = new DatagramSocket();
  18.  
  19.  
  20.         //para recibir y enviar datos
  21.  
  22.            byte[] datosEnviados = new byte[1024];
  23.            byte[] datosRecibidos = new byte[1024];
  24.  
  25.  
  26.            InetAddress IPServidor = InetAddress.getByName(...); //En el paréntesis iría el número de ip del servidor adonde quiero mandarlo
  27.            int puerto = 6000;
  28.  
  29.            ArrayList<Integer> numeros = new ArrayList<>();
  30.  
  31.            while(true) {
  32.  
  33.             //Rellenamos ArrayList numeros
  34.  
  35.             for(int i=0; i<4;i++) {
  36.            System.out.println("Introduce un mensaje: ");
  37.            cadena = in.readLine();
  38.            numeros.add(Integer.parseInt(cadena));    
  39.             }
  40.  
  41.  
  42.             //Empaquetamos ArrayList en bytes para poder enviarlo al servidor
  43.  
  44.             ByteArrayOutputStream out = new ByteArrayOutputStream();
  45.             ObjectOutputStream outputStream = new ObjectOutputStream(out);
  46.             outputStream.writeObject(numeros);
  47.             byte[] listData = out.toByteArray();
  48.  
  49.  
  50.            DatagramPacket envio = new DatagramPacket(listData, listData.length, IPServidor, puerto);
  51.            clientSocket.send(envio);
  52.            outputStream.close();
  53.  
  54.  
  55.            //recibimos respuesta del servidor
  56.  
  57.            DatagramPacket recibo = new DatagramPacket(datosRecibidos, datosRecibidos.length);
  58.            System.out.println("Esperando datagrama...");
  59.            clientSocket.receive(recibo);
  60.            String numero = new String(recibo.getData());
  61.  
  62.                //Si el dato que devuelve el servidor es "x", salimos del bucle y se cierra el cliente      
  63.            if (numero.equals("x")) {
  64.                break;          
  65.            }        
  66.            System.out.println("\t Datos: " + numero);      
  67.  
  68.            } //Fin While
  69.  
  70.            clientSocket.close(); //Cerramos cliente
  71.        }
  72.  
  73.    }
  74.  



Mod: Obligatorio el uso de etiquetas GeSHi para sources.


« Última modificación: 27 Mayo 2019, 16:13 pm por #!drvy » En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: Cómo enviar un ArrayList del cliente al servidor usando UDP?
« Respuesta #1 en: 28 Mayo 2019, 17:38 pm »

Hay tienes para que te aburras más de lo que estás.

Tienes malas prácticas, debes mejorarlas dog, aqui algunos tips a repasar

* Método main hyper recargado, separa la lógica del negocio para que tu api sea mas usable, mi ejemplo no es el mejor, pero esa es la idea.
 * Falta del uso de try-with resources
 * Usa java.util.List en ves de java.awt.List
 * Usa un buen IDE, o aprende a usar bien el que tienes
 * Usa un analizador de código estático como sonar o findbugs
 * Por cada datagrama UDP enviado desde el server, en el cliente debes crear también la cantidad igual o sea,
 new DatagramPacket()
 * Wrappers, las clases de bajo nivel con las de alto nivel, ByteArray de Input/OutputStream, envuélvelos/wrapper con otras clases de alto nivel, mas o menos como hiciste con ObjectInputStream, pero hazlo mas legible.




* Pues hace lo que se pide, introduce 4 número para llenar la java.util.List no la q estabas usando, error primordial.
* Son procesados en el servidor UDP para ser luego retornados
* Si en esos números introducidos está un asterisco, lo usamos como flag, para salirnos del while del cliente, e invocar a
.close(), otra cosa es que la conexión UDP se cierra distinto a la tcp, al invocar a .close() este libera el puerto usado por ese socket, pero segun lo que veo, el puerto queda si escaneamos en windows con un netstat -aon, pero sin poderse usar, con UDP, no hay garantía de la entrega de datagramas que viajan por la red, esto último se parece a la frase en mi blog, pero esta es más *****  >:D


Usa GeSHi


Código
  1. import java.util.logging.Logger;
  2.  
  3. /**
  4.  * interface con Logger
  5.  */
  6. public interface UDPLogger {
  7.  
  8.    default void info(final String info) {
  9.        Logger.getLogger("UdpLogger").info(info);
  10.    }
  11.  
  12.    default void error(final String error) {
  13.        Logger.getLogger("UdpLogger").warning(error);
  14.    }
  15. }
  16.  

Server PoC

Código
  1. package com.foro;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.net.DatagramPacket;
  8. import java.net.DatagramSocket;
  9. import java.time.Instant;
  10. import java.time.ZoneId;
  11. import java.time.format.DateTimeFormatter;
  12. import java.util.Locale;
  13. import java.util.Objects;
  14. import java.util.concurrent.CompletableFuture;
  15. import java.util.concurrent.ExecutorService;
  16. import java.util.concurrent.Executors;
  17.  
  18.  
  19. /**
  20.  * @author rub´n
  21.  */
  22. public class ServerUDPListaProcesarPoC implements UDPLogger {
  23.  
  24.    private static final int PUERTO = 13;
  25.    private ExecutorService es = Executors.newFixedThreadPool(50);
  26.  
  27.    /**
  28.      * Unico constructor de esta clase
  29.      */
  30.    public ServerUDPListaProcesarPoC() {
  31.        /*
  32.          * Async
  33.          */
  34.        CompletableFuture.runAsync(this::initServer, es);
  35.    }
  36.  
  37.    /**
  38.      * Equivalen a 2 datagramas aka UDP packets
  39.      *
  40.      * dos metodos que ejecutara el server al cliente
  41.      * la hora y la lista de numeros procesadas con la formula (n1 + n2 ) * n3 - n4;
  42.      *  - enviarHoraAlCliente(datagramSocket, request);
  43.      *  - enviarListaProcesadaAlCliente(datagramSocket, request);
  44.      *
  45.      */
  46.    private void initServer() {
  47.  
  48.        try (final DatagramSocket datagramSocket = new DatagramSocket(PUERTO)) {
  49.            info("Servidor UDP iniciado correctamente por el puerto: " + PUERTO);
  50.            while (Boolean.TRUE) {
  51.                try {
  52.                    final byte[] byteBuffer = new byte[1024];
  53.                    final DatagramPacket request = new DatagramPacket(byteBuffer, byteBuffer.length);
  54.                    datagramSocket.receive(request);
  55.  
  56.                    enviarHoraAlCliente(datagramSocket, request);
  57.                    enviarListaProcesadaAlCliente(datagramSocket, request);
  58.  
  59.                } catch (IOException | RuntimeException e) {
  60.                    error(e.toString());
  61.                }
  62.            }
  63.        } catch (IOException e) {
  64.            error(e.toString());
  65.        }
  66.    }
  67.  
  68.    /**
  69.      * enviar hora al cliente
  70.      *
  71.      * @param request
  72.      * @param socket
  73.      */
  74.    private void enviarHoraAlCliente(final DatagramSocket socket, final DatagramPacket request) {
  75.        /*
  76.          * Metodo que obtiene la hora como ejemplo
  77.          * solo ejemplo :D
  78.          */
  79.        final byte[] data = getHora().getBytes();
  80.        /*
  81.          * Este datagrama se le enviara como respuesta al cliente
  82.          */
  83.        final DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
  84.        try {
  85.            /*
  86.              * Enviando datos al cliente
  87.              */
  88.            socket.send(response);
  89.        } catch (IOException e) {
  90.            error(e.toString());
  91.        }
  92.  
  93.        /*
  94.          * Imprimimos el datagrama UDP originado, junto con la direccion ip del cliente mas el puerto
  95.          */
  96.        info(new String(data) + " - " + request.getAddress() + ":" + request.getPort());
  97.    }
  98.  
  99.    /**
  100.      * @param socket
  101.      * @param request
  102.      */
  103.    private void enviarListaProcesadaAlCliente(final DatagramSocket socket, final DatagramPacket request) {
  104.        /*
  105.          * Request
  106.          */
  107.        final byte[] data = procesarLista(request);
  108.        final DatagramPacket response = new DatagramPacket(data, data.length, request.getAddress(), request.getPort());
  109.  
  110.        try {
  111.            /*
  112.              * Enviando datos al cliente
  113.              */
  114.            socket.send(response);
  115.        } catch (IOException e) {
  116.            error(e.toString());
  117.        }
  118.        /*
  119.          * Imprimimos el datagrama UDP originado, junto con la direccion ip del cliente mas el puerto
  120.          */
  121.        info(new String(data) + " - " + request.getAddress() + ":" + request.getPort());
  122.    }
  123.  
  124.    /**
  125.      * (n1+n2)*n3-n4
  126.      * procesar lista aqui, o sea, leeremos esos bytes de la siguiente manera
  127.      *
  128.      */
  129.    private byte[] procesarLista(final DatagramPacket listaEnFormaDeBytes) {
  130.        /*
  131.          * Wrappers, y escritos con Try-With resources
  132.          * constructor usado ByteArrayInputStream(byte buf[], int offset, int length)
  133.          * para evitar que el datagrama contenga algun valor mother fucker
  134.          */
  135.        try (final ByteArrayInputStream byteArray = new ByteArrayInputStream(listaEnFormaDeBytes.getData(), listaEnFormaDeBytes.getOffset(), listaEnFormaDeBytes.getLength());
  136.             final InputStreamReader inputStreamReader = new InputStreamReader(byteArray);
  137.             final BufferedReader br = new BufferedReader(inputStreamReader)) {
  138.  
  139.            String line;
  140.            String asterisco = "";
  141.            final StringBuilder sb = new StringBuilder();
  142.            while (Objects.nonNull(line = br.readLine())) {
  143.                if (line.contains("*")) {
  144.                    asterisco = line.trim();
  145.                    break;
  146.                }
  147.                sb.append(line);
  148.            }
  149.  
  150.            if (asterisco.trim().contains("*")) {//si hay asterisco, obtenemos sus bytes
  151.                return "*".getBytes();
  152.            } else {
  153.                final String sLine = sb.toString().trim();
  154.                final int n1 = Integer.parseInt(sLine.split("-")[0]);
  155.                final int n2 = Integer.parseInt(sLine.split("-")[1]);
  156.                final int n3 = Integer.parseInt(sLine.split("-")[2]);
  157.                final int n4 = Integer.parseInt(sLine.split("-")[3]);
  158.  
  159.                final int iResultado = (n1 + n2) * n3 - n4;
  160.                return ("-> Resultado (n1 + n2 ) * n3 - n4: " + iResultado).getBytes();
  161.            }
  162.        } catch (IOException ex) {
  163.            error(ex.toString());
  164.        }
  165.        return new byte[0];//cero en caso de algún error
  166.    }
  167.  
  168.    /**
  169.      *
  170.      * @return String con la hora formateada
  171.      */
  172.    private String getHora() {
  173.        return DateTimeFormatter.ofPattern("eeee, d  'de' MMMM 'de' uuuu hh:mm:ssS a")
  174.                .withLocale(Locale.getDefault())
  175.                .withZone(ZoneId.systemDefault())
  176.                .format(Instant.now());
  177.    }
  178.  
  179.    public static void main(String... queVivaLaPachamama) {
  180.        new ServerUDPListaProcesarPoC();
  181.    }
  182.  
  183. }

Cliente PoC

Código
  1. package com.foro;
  2.  
  3. import java.io.IOException;
  4. import java.net.DatagramPacket;
  5. import java.net.DatagramSocket;
  6. import java.net.InetAddress;
  7. import java.nio.charset.StandardCharsets;
  8. import java.util.List;
  9. import java.util.Scanner;
  10. import java.util.concurrent.CopyOnWriteArrayList;
  11.  
  12. import javax.swing.JOptionPane;
  13.  
  14.  
  15. /**
  16.  * @author rub´n
  17.  */
  18. public class ClientUDPListaProcesarPoC implements UDPLogger {
  19.  
  20.    private static final int PUERTO = 13;
  21.    private final byte[] byteBuffer = new byte[1024]; //1k
  22.    private static final Scanner LEER = new Scanner(System.in);
  23.    private Boolean isFinished = Boolean.FALSE;
  24.  
  25.    /*
  26.      * Unico constructor de esta clase
  27.      */
  28.    public ClientUDPListaProcesarPoC() {
  29.        initClientUDP();
  30.    }
  31.  
  32.    private Boolean isFinished() {
  33.        return isFinished;
  34.    }
  35.  
  36.    private void initClientUDP() {
  37.  
  38.        while (!isFinished()) {
  39.            try (final DatagramSocket socket = new DatagramSocket(0)) {// Cero, produce un puerto aleatorio
  40.  
  41.                socket.setSoTimeout(5000); //5 segundos de tiempo de espera maximo
  42.                final InetAddress localHost = InetAddress.getLocalHost();//conexion con localhost
  43.                final DatagramPacket request = new DatagramPacket(byteBuffer, byteBuffer.length, localHost, PUERTO);
  44.  
  45.                final byte[] listaParaProcesarEnServidor = getListaParaProcesarEnServidor();
  46.  
  47.  
  48.                request.setData(listaParaProcesarEnServidor);
  49.                /*
  50.                  * enviando los datos al servidor
  51.                  */
  52.                socket.send(request);
  53.  
  54.                /*
  55.                  * leyendo respuesta del server
  56.                  */
  57.                respuestasDelServidor(socket);
  58.  
  59.            } catch (IOException e) {
  60.                error(e.toString());
  61.            }
  62.        }
  63.  
  64.  
  65.    }
  66.  
  67.    /**
  68.      * @param socket
  69.      */
  70.    private void respuestasDelServidor(final DatagramSocket socket) {
  71.        /*
  72.          * Aqui craremos 2 datagramas uno para la fecha y otro para la lista
  73.          * el primer datagrama equivale a la fecha, solo de ejemplo
  74.          */
  75.        try {
  76.            final DatagramPacket response = new DatagramPacket(byteBuffer, byteBuffer.length);
  77.            socket.receive(response);
  78.            final String dataGrama1 = new String(response.getData(), response.getOffset(), response.getLength(), StandardCharsets.UTF_8);
  79.            info(dataGrama1);
  80.  
  81.            /*
  82.              * En este datagrama si viene la lista con el resultado
  83.              */
  84.            final DatagramPacket response2 = new DatagramPacket(byteBuffer, byteBuffer.length);
  85.            socket.receive(response2);
  86.            final String dataGrama2 = new String(response2.getData(), response2.getOffset(), response2.getLength(), StandardCharsets.UTF_8);
  87.  
  88.            if (dataGrama2.equals("*")) {
  89.                info("Conexion cerrada");
  90.                JOptionPane.showMessageDialog(null, "Conexion cerrada.");
  91.                socket.close();
  92.                isFinished = Boolean.TRUE; //flag para salir del while de este cliente
  93.            }
  94.            info(dataGrama2);
  95.        } catch (IOException e) {
  96.            error(e.toString());
  97.        }
  98.    }
  99.  
  100.    /**
  101.      * @return byte[] que seran enviados al Servidor para procesar
  102.      */
  103.    private byte[] getListaParaProcesarEnServidor() {
  104.  
  105.     final List<String> listaNumeros = new CopyOnWriteArrayList<>();
  106.        info("Introduce 4 numeros, o (*) para cerrar conexión");
  107.        for (int f = 0; f < 4; f++) {
  108.            info("Introduce numero " + (f + 1));
  109.            final String value = LEER.next().trim();
  110.            if (value.contains("*")) {//si contiene es *, salir del for
  111.                listaNumeros.add(value);
  112.                break;
  113.            }
  114.            listaNumeros.add(value);
  115.        }
  116.  
  117.        /*
  118.          * String retornado con metodo join mas concatenacion de - entre sus numeros
  119.          * para usarlos como flag en el server desde la línea 153
  120.          * por ultimo invocamos a getBytes() gracias al paso anterior
  121.          */
  122.        return String.join("-", listaNumeros).getBytes();
  123.    }
  124.  
  125.    public static void main(String... MaduroMotherFucker) {
  126.        new ClientUDPListaProcesarPoC();
  127.    }
  128.  
  129. }


Versión Server PoC con builder básico.

Código
  1. package com.foro;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.ByteArrayInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.net.DatagramPacket;
  8. import java.net.DatagramSocket;
  9. import java.util.concurrent.CompletableFuture;
  10. import java.util.concurrent.ExecutorService;
  11. import java.util.concurrent.Executors;
  12. import static java.util.Objects.nonNull;
  13.  
  14. /**
  15.  * @author rub´n
  16.  *
  17.  *
  18.     ServerUDPListaProcesarPoC.newBuilder()
  19.         .conPuertoMasBufferSize(13, 1024)
  20.         .conFlagParaCerrarPuerto("*")
  21.         .conNumeroDeHilos(50)
  22.         .crearSocketUdp()
  23.         .respuesta()
  24.         .build();
  25.  
  26.  */
  27. public class ServerUDPListaProcesarPoC implements UDPLogger {
  28.  
  29.    private int puerto;
  30.    private int bufferSize;
  31.    private int numeroHilos;
  32.    private DatagramSocket socket;
  33.    private DatagramPacket datagramPacket;
  34.    private String flagParaCerrarPuerto;
  35.    private ExecutorService es;
  36.  
  37.    /**
  38.      * Unico constructor de esta clase
  39.      */
  40.    private ServerUDPListaProcesarPoC() {
  41.    }
  42.  
  43.    public static ServerUDPListaProcesarPoC newBuilder() {
  44.        return new ServerUDPListaProcesarPoC();
  45.    }
  46.  
  47.    public ServerUDPListaProcesarPoC conNumeroDeHilos(int numeroDeHilos) {
  48.        es = Executors.newFixedThreadPool(numeroDeHilos);
  49.        return this;
  50.    }
  51.  
  52.    public ServerUDPListaProcesarPoC conPuertoMasBufferSize(final int puerto, final int bufferSize) {
  53.        this.bufferSize = bufferSize;
  54.        this.puerto = puerto;
  55.        return this;
  56.    }
  57.  
  58.    public ServerUDPListaProcesarPoC conFlagParaCerrarPuerto(final String flag) {
  59.        this.flagParaCerrarPuerto = flag;
  60.        return this;
  61.    }
  62.  
  63.    public ServerUDPListaProcesarPoC build() {
  64.        return new ServerUDPListaProcesarPoC();
  65.    }
  66.  
  67.    /**
  68.      * Equivalen a 2 datagramas aka UDP packets
  69.      * <p>
  70.      * dos metodos que ejecutara el server al cliente
  71.      * la hora y la lista de numeros procesadas con la formula (n1 + n2 ) * n3 - n4;
  72.      * - enviarHoraAlCliente(datagramSocket, request);
  73.      * - enviarListaProcesadaAlCliente(datagramSocket, request);
  74.      */
  75.    private ServerUDPListaProcesarPoC crearSocketUdp() {
  76.            try {
  77.                this.socket = new DatagramSocket(puerto);
  78.                info("Servidor UDP iniciado correctamente por el puerto: " + puerto);
  79.  
  80.            } catch (IOException e) {
  81.                error(e.toString());
  82.            }
  83.        return this;
  84.    }
  85.  
  86.    public ServerUDPListaProcesarPoC respuesta() {
  87.       CompletableFuture.runAsync(() -> {
  88.            while (Boolean.TRUE) {
  89.                final byte[] byteBuffer = new byte[bufferSize];
  90.                this.datagramPacket = new DatagramPacket(byteBuffer, byteBuffer.length);
  91.                try {
  92.                    this.socket.receive(datagramPacket);
  93.                } catch (IOException e) {
  94.                    e.printStackTrace();
  95.                }
  96.                enviarHoraAlCliente();
  97.                enviarListaProcesadaAlCliente();
  98.            }
  99.        },es);
  100.        return this;
  101.    }
  102.  
  103.    /**
  104.      * enviar hora al cliente
  105.      *
  106.      */
  107.    private ServerUDPListaProcesarPoC enviarHoraAlCliente() {
  108.        /*
  109.          * Metodo que obtiene la hora como ejemplo
  110.          * solo ejemplo :D
  111.          */
  112.        final byte[] data = getHora().getBytes();
  113.        /*
  114.          * Este datagrama se le enviara como crearSocketUdp al cliente
  115.          */
  116.        final DatagramPacket response = new DatagramPacket(data, data.length, this.datagramPacket.getAddress(), this.datagramPacket.getPort());
  117.        try {
  118.            /*
  119.              * Enviando datos al cliente
  120.              */
  121.            this.socket.send(response);
  122.        } catch (IOException e) {
  123.            error(e.toString());
  124.        }
  125.  
  126.        /*
  127.          * Imprimimos el datagrama UDP originado, junto con la direccion ip del cliente mas el puerto
  128.          */
  129.        info(new String(data) + " - " + datagramPacket.getAddress() + ":" + datagramPacket.getPort());
  130.        return this;
  131.    }
  132.  
  133.    /**
  134.      */
  135.    private ServerUDPListaProcesarPoC enviarListaProcesadaAlCliente() {
  136.        /*
  137.          * Request
  138.          */
  139.        final byte[] data = procesarLista(datagramPacket);
  140.        final DatagramPacket respuestaAlCliente = new DatagramPacket(data, data.length, datagramPacket.getAddress(), datagramPacket.getPort());
  141.  
  142.        try {
  143.            /*
  144.              * Enviando datos al cliente
  145.              */
  146.            this.socket.send(respuestaAlCliente);
  147.        } catch (IOException e) {
  148.            error(e.toString());
  149.        }
  150.        /*
  151.          * Imprimimos el datagrama UDP originado, junto con la direccion ip del cliente mas el puerto
  152.          */
  153.        info(new String(data) + " - " + datagramPacket.getAddress() + ":" + datagramPacket.getPort());
  154.        return this;
  155.    }
  156.  
  157.    /**
  158.      * (n1+n2)*n3-n4
  159.      * procesar lista aqui, o sea, leeremos esos bytes de la siguiente manera
  160.      */
  161.    private byte[] procesarLista(final DatagramPacket listaEnFormaDeBytes) {
  162.        /*
  163.          * Wrappers, y escritos con Try-With resources
  164.          * constructor usado ByteArrayInputStream(byte buf[], int offset, int length)
  165.          * para evitar que el datagrama contenga algun valor mother fucker
  166.          */
  167.        try (final ByteArrayInputStream byteArray = new ByteArrayInputStream(listaEnFormaDeBytes.getData(),
  168.                listaEnFormaDeBytes.getOffset(), listaEnFormaDeBytes.getLength());
  169.             final InputStreamReader inputStreamReader = new InputStreamReader(byteArray);
  170.             final BufferedReader br = new BufferedReader(inputStreamReader)) {
  171.  
  172.            String line;
  173.            String asterisco = "";
  174.            final StringBuilder sb = new StringBuilder();
  175.            while (nonNull(line = br.readLine())) {
  176.                if (line.contains(flagParaCerrarPuerto)) {
  177.                    asterisco = line.trim();
  178.                    break;
  179.                }
  180.                sb.append(line);
  181.            }
  182.  
  183.            if (asterisco.trim().contains(flagParaCerrarPuerto)) {//si hay asterisco, obtenemos sus bytes
  184.                return flagParaCerrarPuerto.getBytes();
  185.            } else {
  186.                final String sLine = sb.toString().trim();
  187.                final int n1 = Integer.parseInt(sLine.split("-")[0]);
  188.                final int n2 = Integer.parseInt(sLine.split("-")[1]);
  189.                final int n3 = Integer.parseInt(sLine.split("-")[2]);
  190.                final int n4 = Integer.parseInt(sLine.split("-")[3]);
  191.  
  192.                final int iResultado = (n1 + n2) * n3 - n4;
  193.                return ("-> Resultado (n1 + n2 ) * n3 - n4: " + iResultado).getBytes();
  194.            }
  195.        } catch (IOException ex) {
  196.            error(ex.toString());
  197.        }
  198.        return new byte[0];//cero en caso de algún error
  199.    }
  200.  
  201.    public static void main(String... queVivaLaPachamama) {
  202.        ServerUDPListaProcesarPoC.newBuilder()
  203.                .conPuertoMasBufferSize(13, 1024)
  204.                .conFlagParaCerrarPuerto("*")
  205.                .conNumeroDeHilos(50)
  206.                .crearSocketUdp()
  207.                .respuesta()
  208.                .build();
  209.    }
  210.  
  211. }
  212.  


« Última modificación: 5 Junio 2019, 16:19 pm por rub'n » En línea



rubn0x52.com KNOWLEDGE  SHOULD BE FREE.
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen ki
Serapis
Colaborador
***
Desconectado Desconectado

Mensajes: 3.348


Ver Perfil
Re: Cómo enviar un ArrayList del cliente al servidor usando UDP?
« Respuesta #2 en: 28 Junio 2019, 16:01 pm »

Citar
Soy un novato en esto de conexiones TCP/UDP, seguro que me habré equivocado pero no sé como solucionarlo
...
espero podáis orientarme un poco, porque estoy más perdido que un pulpo en un garaje.
...
Quiero enviar una lista de números al servidor para que este al leerlos efectúe las operaciones correspondientes y......... devuelva el resultado de las mismas al cliente. Luego volverá a pedir números al cliente y de nuevo le devolverá el resultado correspondiente, repitiéndose el proceso hasta que el cliente introduzca un *, entonces ahí se cerraría conexión con el servidor. Tengo que hacerlo obligatoriamente utilizando protocolo UDP.

Tú dí lo que quieras, pero esto apesta a virus que tira para atrás... incluso ese descargo de intenciones del 'pulpo perdido en el garage', hace que apeste todavía más...

El protocolo UDP, no se inventó para envío masivo de datos, el que se empeña en ello, no puede tener otra finalidad que camuflar la comunicación de un troyano...

Es lo mismo que si un tipo dice que quiere enviar 1000 toneladas de piezas metálicas pero que lo haga un ciclista pieza a pieza... un volumen grande se envía en camiones, trenes, etc... es más rápido y más barato. ...un transportista deja firma en albaranes, partidas de transporte, horarios, etc... que pueden rastrearse. Hacerlo a 'pequeña' escala solo puede tener malas intenciones, a base de no llamar la atención. Así que si alguien quiere mover 1000 toneladas de piezas en bicicleta, lo siento pero pensar que se trata de un terrorista pasa a ser la primera (y probablemente la única) sospecha.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines