Download Sockets en Java - PoliformaT
Document related concepts
no text concepts found
Transcript
Diseño Y Aplicaciones de Sistemas Distribuidos Sockets en Java Joan Vila DISCA / UPV Departament d’Informàtica de Sistemes i Computadors Universitat Politècnica de València Sockets en Java Indice – Comunicación orientada a conexión: Sockets TCP – Datagramas: Sockets UDP – Multicast Procesamiento distribuido en Java © Joan Vila 35 Sockets en Java Sockets en Java El API de Java a los sockets TCP/IP se fundamenta en las siguientes clases: – Comunicación con conexión: sockets TCP clase Socket : la utilizan los clientes clase ServerSocket : la utilizan los servidores – Comunicación sin conexión (datagramas): sockets UDP clase DatagramSocket clase DatagramPacket – Difusión de datagramas: sockets Multicast clase MulticastSocket Procesamiento distribuido en Java © Joan Vila 36 Sockets en Java Protocolos con conexión versus sin conexión Sin conexión Con Conexión Origen Origen Procesamiento distribuido en Java Destino Destino © Joan Vila 37 Sockets TCP Sockets TCP: el cliente – La clase socket Socket s = new Socket(server, port); OutputStream os = s.getOutputStream(); InputStream is = s.getInputStream(); s.close(); Sockets TCP: el servidor – La clase ServerSocket ServerSocket servSock = new ServerSocket(port); Socket clientSock = servSocket.accept(); servSock.close(); Procesamiento distribuido en Java © Joan Vila 38 Sockets TCP Cliente de echo TCP (ASCII) import java.io.*; import java.net.*; public class Echo { public static void main(String[] args) { if (args.length<2) { System.out.println("Uso: echo host port"); System.exit(1); } Socket echoSocket = null; OutputStream os = null; InputStream is = null; ... Procesamiento distribuido en Java © Joan Vila 39 Sockets TCP Cliente de echo TCP (ASCII) public class Echo { public static void main(String[] args) { ... try { echoSocket = new Socket(args[0],Integer.parseInt(args[1])); os = echoSocket.getOutputStream(); is = echoSocket.getInputStream(); } catch (UnknownHostException e) { System.err.println("Don't know about host: "+args[0]); } catch (IOException e) { System.err.println("Couldn't get I/O for connection to: "+args[0]); } Procesamiento distribuido en Java © Joan Vila 40 Sockets TCP Cliente de echo TCP (ASCII) public class Echo { public static void main(String[] args) { ... if (echoSocket != null && os != null && is != null) { try { byte[] bufferin = new byte[256]; byte[] bufferout = new byte[256]; int count; String salida; while ((count = System.in.read(bufferin)) != -1) { os.write(bufferin,0,count); count=is.read(bufferout); salida = new String(bufferout,0,count); System.out.print("echo: " + salida); if (salida.equals("Bye"+"\r\n")) break; } distribuido en Java Procesamiento © Joan Vila 41 Sockets TCP Cliente de echo TCP (ASCII) public class Echo { public static void main(String[] args) { ... if (echoSocket != null && os != null && is != null) { try { ... os.close(); is.close(); echoSocket.close(); } catch (IOException e) { System.err.println("I/O failed on connection to: "+args[0]); } } } } Procesamiento distribuido en Java © Joan Vila 42 Sockets TCP Servidor de echo TCP multihilo (Unicode) class EchoMultiServer { public static void main(String[] args) { ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(7); } catch (IOException e) { System.err.println("Could not listen on port: 7, " + e.getMessage()); System.exit(1); } System.out.println("EchoMultiServer listening on port: 7"); Procesamiento distribuido en Java © Joan Vila 43 Sockets TCP Servidor de echo TCP multihilo (Unicode) class EchoMultiServer { public static void main(String[] args) { ... while (listening) { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed on port: 7, " + e.getMessage()); continue; } new EchoMultiServerThread(clientSocket).start(); } try { serverSocket.close(); } catch (IOException e) { System.err.println("Could not close server socket." + e.getMessage()); } } } Procesamiento distribuido en Java © Joan Vila 44 Sockets TCP Servidor de echo TCP multihilo (Unicode) class EchoMultiServerThread extends Thread { Socket clientSocket = null; EchoMultiServerThread(Socket socket) { super("EchoMultiServerThread"); clientSocket = socket; } Ojo!: caracteres Unicode public void run() { try { BufferedReader is = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); PrintWriter os = new PrintWriter(clientSocket.getOutputStream()); String inputLine; Procesamiento distribuido en Java © Joan Vila 45 Sockets TCP Servidor de echo TCP multihilo (Unicode) class EchoMultiServerThread extends Thread { ... public void run() { ... while ((inputLine = is.readLine()) != null) { os.println(inputLine); os.flush(); } os.close(); is.close(); clientSocket.close(); } catch (IOException e) { System.err.println("Error sending/receiving" + e.getMessage()); e.printStackTrace(); } } } Procesamiento distribuido en Java © Joan Vila 46 Sockets UDP Sockets UDP: el cliente DatagramSocket socket = new DatagramSocket(); // send packet byte[] msg = {'H', 'e', 'l', 'l', 'o'}; port = Integer.parseInt(args[1]); address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(msg, lenght, address, port); socket.send(packet); // receive packet byte[] buf = new byte[4096]; packet = new DatagramPacket(buf, 256); socket.receive(packet); socket.close(); Procesamiento distribuido en Java © Joan Vila 47 Sockets UDP Sockets UDP: el servidor DatagramSocket socket = new DatagramSocket(7); DatagramPacket packet = new DatagramPacket(buf,4096); // receive packet socket.receive(packet); String received = new String(packet.getData(),0,packet.getLength()); Procesamiento distribuido en Java © Joan Vila 48 Sockets multicast Sockets multicast // join a Multicast group and send the group salutations byte[] msg = {'H', 'e', 'l', 'l', 'o'}; InetAddress group = InetAddress.getByName("228.5.6.7"); MulticastSocket s = new MulticastSocket(6789); s.joinGroup(group); DatagramPacket hi = new DatagramPacket(msg, msg.length, group, 6789); s.send(hi); // get their responses! byte[] buf = new byte[1000]; DatagramPacket recv = new DatagramPacket(buf, buf.length); s.receive(recv); ... // OK, I'm done talking - leave the group... s.leaveGroup(group); Procesamiento distribuido en Java © Joan Vila 49