Aplicaciones Cliente-Servidor Con Datagramas
User Datagram Protocol (UDP) UDP es un protocolo que no garantiza la comunicación entre dos aplicaciones. No está basado en conexión. Envía paquetes de datos independientes conocidos como datagramas. Análogo a enviar una carta por correo. Puerto # Datos Datagrama (paquete UDP) Cecilia M. Curlango Rosas 2/21
Qué es un datagrama? Un datagrama es un mensaje independiente y auto contenido que se envía por la red y cuyo arribo, tiempo de arribo y contenido no se garantizan. Una aplicación envía y recibe DatagramPacket a través de un DatagramSocket para implementar la comunicación utilizando UDP. Se pueden enviar paquetes a varios clientes que están escuchando en un MulticastSocket. Cecilia Curlango Rosas 3/21
DatagramPacket Cecilia Curlango Rosas 4/21
DatagramSocket Cecilia Curlango Rosas 5/21
Qué hacen los métodos? getsotimeout() y setsotimeout() send() y receive() Cecilia Curlango Rosas 6/21
Ejemplo Cliente-Servidor QuoteServer Red QuoteClient QuoteServerThread Cecilia Curlango Rosas 7/21
Clase QuoteServer public class QuoteServer { public static void main(string[] args) throws IOException { new QuoteServerThread().start(); Cecilia Curlango Rosas 8/21
Clase QuoteServerThread public class QuoteServerThread extends Thread { protected DatagramSocket socket = null; protected BufferedReader in = null; protected boolean morequotes = true; public QuoteServerThread() throws IOException { this("quoteserver"); public QuoteServerThread(String name) throws IOException { super(name); socket = new DatagramSocket(4445); try { in = new BufferedReader( new FileReader("one-liners.txt")); catch (FileNotFoundException e) System.err.println("Couldn't open quote file. " + "Serving time instead."); Cecilia Curlango Rosas 9/21
Clase QuoteServerThread public void run() { while (morequotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // figure out response String dstring = null; if (in == null) dstring = new Date().toString(); else dstring = getnextquote(); buf = dstring.getbytes(); // send the response to the client at "address" and "port" InetAddress address = packet.getaddress(); int port = packet.getport(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); catch (IOException e) { e.printstacktrace(); morequotes = false; socket.close(); Cecilia Curlango Rosas 10/21
Clase QuoteServerThread protected String getnextquote() { String returnvalue = null; try { if ((returnvalue = in.readline()) == null) { in.close(); morequotes = false; returnvalue = "No more quotes. Goodbye."; catch (IOException e) { returnvalue = "IOException occurred in server."; return returnvalue; Cecilia Curlango Rosas 11/21
Clase QuoteClient public class QuoteClient { public static void main(string[] args) throws IOException { if (args.length!= 1) { System.out.println("Usage: java QuoteClient <hostname>"); return; // get a datagram socket DatagramSocket socket = new DatagramSocket(); // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData(), 0, packet.getlength()); System.out.println("Quote of the Moment: " + received); socket.close(); Cecilia Curlango Rosas 12/21
Transmisión a múltiples receptores Cecilia Curlango Rosas 13/21
MulticastSocket Esta clase sirve para enviar y recibir paquetes IP multicast. Un MulticastSocket es un DatagramSocket con capacidad adicional para unirse a grupos de otros hosts en la Internet. Un grupo multicast se especifica con una dirección IP clase D y un número de puerto UDP. Las direcciones IP de clase D están en el rango de 224.0.0.0 a 239.255.255.255. Pero, la dirección 224.0.0.0 está reservada y no debe usarse. Cecilia Curlango Rosas 14/21
MulticastSocket Cecilia Curlango Rosas 15/21
Ejemplo Transmisión a múltiples receptores MulticastServer Red MulticastClient QuoteServerThread MulticastServerThread Cecilia Curlango Rosas 16/21
MulticastServer public class MulticastServer { public static void main(string[] args) throws java.io.ioexception { new MulticastServerThread().start(); Cecilia Curlango Rosas 17/21
public class MulticastServerThread extends QuoteServerThread { private long FIVE_SECONDS = 5000; public MulticastServerThread() throws IOException { super("multicastserverthread"); public void run() { while (morequotes) { try { byte[] buf = new byte[256]; // construct quote String dstring = null; if (in == null) dstring = new Date().toString(); else dstring = getnextquote(); buf = dstring.getbytes(); // send it InetAddress group = InetAddress.getByName("230.0.0.1"); DatagramPacket packet = new DatagramPacket(buf, buf.length, group, 4446); socket.send(packet); // sleep for a while try { sleep((long)(math.random() * FIVE_SECONDS)); catch (InterruptedException e) { catch (IOException e) { e.printstacktrace(); morequotes = false; socket.close(); 18/21
MulticastClient public class MulticastClient { public static void main(string[] args) throws IOException { MulticastSocket socket = new MulticastSocket(4446); InetAddress address = InetAddress.getByName("230.0.0.1"); socket.joingroup(address); DatagramPacket packet; // get a few quotes for (int i = 0; i < 5; i++) { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData(), 0, packet.getlength()); System.out.println("Quote of the Moment: " + received); socket.leavegroup(address); socket.close(); Cecilia Curlango Rosas 19/21
Ejercicio 1.Modifique el servidor del primer ejemplo para que muestre en su consola un mensaje identificando a cada cliente del que recibe una petición. Deberá mostrar para cada uno la dirección y el puerto del que recibió la petición así como el mensaje Recibí petición de:. 2.Modifique el servidor del segundo ejemplo para que muestre también en consola el mensaje que está transmitiendo a los suscriptores. Cecilia Curlango Rosas 20/21
Referencias Clase DatagramPacket - http://download.oracle.com/javase/7/docs/api/java/net/datagrampacket.html Clase DatagramSocket - http://download.oracle.com/javase/7/docs/api/java/net/datagramsocket.html Tutorial de datagramas - http://download.oracle.com/javase/tutorial/networking/datagrams/index.html Clase MulticastSocket - http://download.oracle.com/javase/7/docs/api/java/net/multicastsocket.html Cecilia Curlango Rosas 21/21