techno-

Cliente UDP

Feb 16th, 2023
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. package es.udc.redes.tutorial.udp.client;
  2.  
  3. import java.net.*;
  4.  
  5. /**
  6.  * Implements an echo client using UDP
  7.  */
  8. public class UdpClient {
  9.  
  10.     public static void main(String argv[]) {
  11.         if (argv.length != 3) {
  12.             System.err.println("Format: es.udc.redes.tutorial.udp.client.UdpClient <server_address> <port_number> <message>");
  13.             System.exit(-1);
  14.         }
  15.         DatagramSocket sDatagram = null;
  16.         try {
  17.  
  18.             // Create a non connection-oriented socket
  19.             // (use any available port)
  20.             sDatagram = new DatagramSocket();
  21.             // Set timeout to 300 secs
  22.             sDatagram.setSoTimeout(300000);
  23.             // Obtain server IP address from first argument
  24.             InetAddress serverAddress = InetAddress.getByName(argv[0]);
  25.             // Obtain server port from second argument
  26.             int serverPort = Integer.parseInt(argv[1]);
  27.             // Obtain message from third argument
  28.             String message = argv[2];
  29.             // Prepare the datagram
  30.             DatagramPacket dgramSent = new DatagramPacket(message.getBytes(),
  31.                     message.getBytes().length, serverAddress, serverPort);
  32.             // Send the datagram
  33.             sDatagram.send(dgramSent);
  34.             System.out.println("CLIENT: Sending "
  35.                     + new String(dgramSent.getData()) + " to "
  36.                     + dgramSent.getAddress().toString() + ":"
  37.                     + dgramSent.getPort());
  38.             // Prepare datagram for data reception
  39.             byte array[] = new byte[1024];
  40.             DatagramPacket dgramRec = new DatagramPacket(array, array.length);
  41.             // Receive the message
  42.             sDatagram.receive(dgramRec);
  43.             System.out.println("CLIENT: Received "
  44.                     + new String(dgramRec.getData(), 0, dgramRec.getLength())
  45.                     + " from " + dgramRec.getAddress().toString() + ":"
  46.                     + dgramRec.getPort());
  47.         } catch (SocketTimeoutException e) {
  48.             System.err.println("Nothing received in 300 secs");
  49.         } catch (Exception e) {
  50.             System.err.println("Error: " + e.getMessage());
  51.         } finally {
  52.             // Close socket to release connection
  53.             sDatagram.close();
  54.         }
  55.     }
  56. }
Add Comment
Please, Sign In to add comment