Foro de elhacker.net

Programación => Java => Mensaje iniciado por: BatchianoISpyxolo en 6 Febrero 2013, 16:30 pm



Título: Servidor y Cliente UDP - echo test
Publicado por: BatchianoISpyxolo en 6 Febrero 2013, 16:30 pm
Bueno, he codificado un cliente-servidor UDP pero mi servidor no logra recibir el paquete datagrama enviado por el cliente ._.

¿Alguna ayudita?

ClienteUDP,java
Código
  1. package proyecto.socketudp;
  2. import java.net.*;
  3. /** Ejemplo que implementa un cliente de eco usando UDP. */
  4. public class ClienteUDP {
  5. public static void main(String argv[]) {
  6. if (argv.length != 3) {
  7. System.err.println("Formato: ClienteUDP <maquina> <puerto> <mensaje>");
  8. System.exit(-1);
  9. }
  10. DatagramSocket sDatagram = null;
  11. try {
  12. // Creamos el socket no orientado a conexión
  13. // (en cualquier puerto libre)
  14. sDatagram = new DatagramSocket();
  15. // Establecemos un timeout de 30 segs
  16. sDatagram.setSoTimeout(30000);
  17. // Obtenemos la dirección IP del servidor
  18. // (recibida en el primer argumento por linea de comandos)
  19. InetAddress dirServidor = InetAddress.getByName(argv[0]);
  20. // Obtenemos el puerto del servidor
  21. // (recibido en el segundo argumento por linea de comandos)
  22. int puertoServidor = Integer.parseInt(argv[1]);
  23. // Obtenemos el mensaje
  24. // (tercer argumento de la linea de comandos)
  25. String mensaje = argv[2];
  26.  
  27. byte[] envInfo = new byte[1024];
  28.       envInfo = mensaje.getBytes();
  29. // Preparamos el datagrama que vamos a enviar y lo enviamos
  30. DatagramPacket envPaquete = new DatagramPacket(
  31. envInfo, envInfo.length,
  32. dirServidor, puertoServidor
  33. );
  34. // Enviamos el datagrama
  35. sDatagram.send(envPaquete);
  36. System.out.println(
  37. "CLIENTE: Enviando "
  38. + new String(envPaquete.getData()) + " a "
  39. + envPaquete.getAddress().toString() + ":"
  40. + envPaquete.getPort()
  41. );
  42.  
  43. // Preparamos el datagrama de recepción
  44. byte[] recInfo = new byte[1024];
  45. DatagramPacket recPaquete = new DatagramPacket(recInfo, recInfo.length);
  46. // Recibimos el mensaje
  47. sDatagram.receive(recPaquete);
  48. System.out.println(
  49. "CLIENTE: Recibido "
  50. + new String(recPaquete.getData(), 0, recPaquete.getLength())
  51. + " de " + recPaquete.getAddress().toString() + ":"
  52. + recPaquete.getPort()
  53. );
  54. } catch (SocketTimeoutException e) {
  55. System.err.println("30 segs sin recibir nada");
  56. } catch (Exception e) {
  57. System.err.println("Error: " + e.getMessage());
  58. } finally {
  59. // Cerramos el socket para liberar la conexión
  60. sDatagram.close();
  61. }
  62. }
  63. }

ServidorUDP.java
Código
  1. package proyecto.socketudp;
  2.  
  3. import java.net.*;
  4. /** Ejemplo que implementa un servidor de eco usando UDP. */
  5. public class ServidorUDP {
  6.    public static void main(String argv[]) throws SocketException {
  7.        if (argv.length != 1) {
  8.            System.err.println("Formato: ServidorUDP <puerto>");
  9.            System.exit(-1);
  10.        }
  11.        try {
  12.            // Creamos el socket datagrama
  13.            DatagramSocket sDatagram = new DatagramSocket(Integer.parseInt(arv[0]));
  14.            // Establecemos un timeout de 30 segs
  15.            sDatagram.setSoTimeout(30000);
  16.            byte array[] = new byte[1024];
  17.            DatagramPacket dgramRec, dgramEnv = null;
  18.            while (true) {
  19.                // Preparamos un datagrama para recepción
  20.                dgramRec = new DatagramPacket(array, array.length);
  21.  
  22.                // Recibimos el mensaje
  23.                sDatagram.receive(dgramRec);
  24.  
  25.                // Recabamos informacion
  26.                String mensaje = new String(dgramRec.getData());
  27.                InetAddress dirCliente = dgramRec.getAddress();
  28.                int puertoCliente = dgramRec.getPort();
  29.  
  30.                System.out.println(
  31.                    "SERVIDOR: Recibido "
  32.                    + new String(dgramRec.getData(), 0, dgramRec.getLength())
  33.                    + " de " + dirCliente.toString() + ":"
  34.                    + puertoCliente
  35.                );
  36.  
  37.                // Preparamos el datagrama que vamos a enviar
  38.                dgramEnv = new DatagramPacket(
  39.                    mensaje.getBytes(), mensaje.getBytes().length,
  40.                    dirCliente, puertoCliente
  41.                );
  42.  
  43.                // Enviamos el mensaje
  44.                sDatagram.send(dgramEnv);
  45.                System.out.println(
  46.                    "SERVIDOR: Enviando"
  47.                    + new String(dgramEnv.getData(), 0, dgramEnv.getLength())
  48.                    + " de " + dgramEnv.getAddress().toString() + ":"
  49.                    + dgramEnv.getPort()
  50.                );
  51.            }
  52.        } catch (SocketTimeoutException e) {
  53.            System.err.println("30 segs sin recibir nada");
  54.        } catch (Exception e) {
  55.            System.err.println("Error: " + e.getMessage());
  56.        }
  57.    }
  58. }


Título: Re: Servidor y Cliente UDP - echo test
Publicado por: BatchianoISpyxolo en 8 Febrero 2013, 14:03 pm
Me respondo a mí mismo por si a alguien más le ayuda.

Al construir el DatagramSocket del servidor debí haber especificado el puerto (que se pasa como primer y único argumento al servidor) en el constructor.