A apresentação está carregando. Por favor, espere

A apresentação está carregando. Por favor, espere

Comunicação em Rede no JAVA

Apresentações semelhantes


Apresentação em tema: "Comunicação em Rede no JAVA"— Transcrição da apresentação:

1 Comunicação em Rede no JAVA
Aspectos básicos Sockets URL’s Nuno Valero Ribeiro Gab. F269 5-dez-18

2 Comunicação através de TCP/IP
Todas as classes de comunicação em rede estão definidas no package java.net. Classes para comunicação através de TCP: Socket, SocketServer, URL, URLConnection. Classes para comunicação através de UDP: DatagramSocket, e DatagramPacket. Nuno Valero Ribeiro Gab. F269 5-dez-18

3 Classe Socket - construtores
Cria um socket sem ligação. Socket(InetAddress addr, int port) Cria um stream socket e liga-o a ao endereço addr e ao porto port. Socket(InetAddress rAddr, int rPort, InetAddress lAaddr, int lPort) Cria um stream socket e liga-o a ao endereço rAddr e ao porto rPort. Associa o socket (bind) ao endereço local lAddr e ao porto local lPort. Socket(String host, int) Cria um stream socket e liga-o a host host e ao porto port. Socket(String rHost, int rPort, InetAddress lAddr, int lPort) Cria um stream socket e liga-o a ao host rHost e ao porto rPort. Associa o socket (bind) ao endereço local lAddr e ao porto local lPort. Nuno Valero Ribeiro Gab. F269 5-dez-18

4 Classe Socket - métodos
close() Fecha o socket. InetAddress getInetAddress() Retorna o endereço a que o socket está ligado. InputStream getInputStream() Retorna um InputStream para o socket. InetAddress getLocalAddress() Retorna o endereço local a que o socket está associado int getLocalPort() Retorna o porto local a que o socket está associado. OutputStream getOutputStream() Retorna um OutputStream para o socket. Int getPort() Retorna o porto remoto a que o socket está ligado. setSoTimeout(int tout) Activa (tout > 0)/ desactiva (tout = 0) a flag SO_TIMEOUT, com o timeout especificado em milisegundos. Nuno Valero Ribeiro Gab. F269 5-dez-18

5 Classe Socket - exemplo
import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: taranis."); } BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); out.close(); in.close(); stdIn.close(); echoSocket.close(); Classe Socket - exemplo Nuno Valero Ribeiro Gab. F269 5-dez-18

6 Classe ServerSocket - construtores
ServerSocket(int port) Cria um ServerSocket associado ao porto port. ServerSocket(int port, int backlog) Cria um ServerSocket associado ao porto port aceitando maxlog ligações ServerSocket(int port, int backlog, InetAddress bindAddr) Cria um ServerSocket associado ao porto port aceitando maxlog ligações e associado ao endereço bindAddr Nuno Valero Ribeiro Gab. F269 5-dez-18

7 Classe ServerSocket - métodos
Socket accept() Espera por ligações no socket. Retorna um novo socket quando a ligação é estabelecida. close() Fecha um ServerSocket. InetAddress getInetAddress() Retorna o endereço local a que o socket está associado. Int getLocalPort() Retorna o porto local a que o socket está associado. Int getSoTimeout() Retorna o estado da flag SO TIMEOUT. setSoTimeout(int) Activa (tout > 0)/ desactiva (tout = 0) a flag SO_TIMEOUT, com o timeout especificado em milisegundos. Nuno Valero Ribeiro Gab. F269 5-dez-18

8 Gab. F269 nribeiro@est.ips.pt
import java.net.*; import java.io.*; class EchoTcpServer { public static void main(String[] args) { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } // ... Socket clientSocket = null; try {clientSocket = serverSocket.accept();} try { BufferedReader is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter os = new PrintWriter(clientSocket.getOutputStream() ), false); String inputLine, outputLine; while ((inputLine = is.readLine()) != null) { System.out.println("inputLine = " + inputLine); outputLine = new String(inputLine); os.println(outputLine); os.flush(); } Nuno Valero Ribeiro Gab. F269 5-dez-18

9 Classe DatagramSocket - construtores
Constructs a datagram socket and binds it to any available port on the local host machine. DatagramSocket(int) Constructs a datagram socket and binds it to the specied port on the local host machine. DatagramSocket(int, InetAddress) Creates a datagram socket, bound to the specied local address. Nuno Valero Ribeiro Gab. F269 5-dez-18

10 Classe DatagramSocket - métodos
close() Closes this datagram socket. getLocalAddress() Gets the local address to which the socket is bound. getLocalPort() Returns the port number on the local host to which this socket is bound. getSoTimeout() Retrive setting for SO TIMEOUT. receive(DatagramPacket) Receives a datagram packet from this socket. send(DatagramPacket) Sends a datagram packet from this socket. setSoTimeout(int) Enable/disable SO TIMEOUT with the specied timeout, in milliseconds. Nuno Valero Ribeiro Gab. F269 5-dez-18

11 Classe DatagramPacket - construtores
DatagramPacket(byte[], int) Constructs a DatagramPacket for receiving packets of length ilength. DatagramPacket(byte[], int, InetAddress, int) Constructs a datagram packet for sending packets of length ilength to the specied port numberon the specied host. Nuno Valero Ribeiro Gab. F269 5-dez-18

12 Classe DatagramPacket - métodos
InetAddress getAddress() Returns the IP address of the machine to which this datagram is being sent or from which the datagram was received. getData() Returns the data received or the data to be sent. Int getLength() Returns the length of the data to be sent or the length of the data received. Int getPort() Returns the port number on the remote host to which this datagram is being sent or from which the datagram was received. setAddress InetAddress) setData (byte[]) setLength (int) setPort(int) Nuno Valero Ribeiro Gab. F269 5-dez-18

13 Classe URL- construtores
URL(String) Creates a URL object from the String representation. URL(String, String, int, String) Creates a URL object from the specied protocol, host, port number, and le. URL(String, String, String) Creates an absolute URL from the specied protocol name, host name, and le name. Nuno Valero Ribeiro Gab. F269 5-dez-18

14 Gab. F269 nribeiro@est.ips.pt
Classe URL - métodos int hashCode() Retorna um inteiro para indexação numa tabela de hash. URLConnection openConnection() Retorna um objecto URLConnection , que representa uma ligação com o objecto referenciado pelo URL InputStream openStream() Abre uma ligação com o URL e retorna um InputStream (equivalente a openConnection().getInputStream() ) boolean sameFile(URL) Compara dois URLs excluindo os campos de referência (ancoras). set(String proto, String host, int port, String file, String ref) Define os vários campos do URL boolean equals(Object) Compara dois URLs. Object getContent() Retorna o conteúdo de um URL (equivalente a openConnection().getContent() ) String getFile() Retorna o nome do ficheiro no URL. String getHost() Retorna o nome do host no URL. int getPort() Retorna o porto no URL. String getProtocol() Retorna o nome do protocolo no URL. String getRef() Retorna a ancora (referência )no URL. Nuno Valero Ribeiro Gab. F269 5-dez-18

15 Gab. F269 nribeiro@est.ips.pt
import java.net.*; import java.io.*; class URLReader { public static void main(String[] args) { try { URL urlRef = new URL(" BufferedReader is = new BufferedReader(new InputStreamReader(urlRef.openStream())); String inputLine; while ((inputLine = is.readLine()) != null) { System.out.println(inputLine); } is.close(); } catch (MalformedURLException me) { System.out.println("MalformedURLException: " + me); } catch (IOException ioe) { System.out.println("IOException: " + ioe); } Nuno Valero Ribeiro Gab. F269 5-dez-18

16 Gab. F269 nribeiro@est.ips.pt
import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { String url; System.out.println("URL: " + args[0]); if(args.length != 0) url = args[0]; else url = " URL aURL = new URL(url); System.out.println("protocol = " + aURL.getProtocol()); System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef()); } Nuno Valero Ribeiro Gab. F269 5-dez-18

17 Gab. F269 nribeiro@est.ips.pt
Classe URLConnection Classe abstracta que representa uma comunicação entre uma aplicação e um URL. Instâncias desta classe podem ser usadas para ler e escrever para o recurso referenciado pelo URL. A criação de uma ligação para um URL envolve os seguintes passos: O objecto URLConnection é obtido através da invocação do método openConnection de um URL. Manipulação dos parâmetros da ligação e das propriedades dos pedidos. Estabelecimento da ligação com o objecto remoto, através do método connect. O objecto remoto fica disponível. Os campos dos cabeçalhos e o conteúdo do objecto podem ser acedidos. Nuno Valero Ribeiro Gab. F269 5-dez-18

18 Classe URLConnection - construtores
protected URLConnection(URL) O construtor desta classe apenas pode ser acedido por classes derivadas. A ligação com o objecto referenciado no URL não é criada. Nuno Valero Ribeiro Gab. F269 5-dez-18

19 Gab. F269 nribeiro@est.ips.pt
Classe URL - métodos Estabelecimento da ligação connect() Definição de parâmetros da ligação setAllowUserIteraction(boolean) setDefaultAllowUserIteraction(boolean) setDoInput(boolean) setDoOutput(boolean) setIfModifiedSince(long) setUseCaches(boolean) setDefaultUseCaches(boolean) Definição das propriedades dos pedidos setRequestProperty(String key, String value) setDefaultRequestProperty(String key, String value) Acesso aos campos do cabeçalho e ao conteúdo do objecto referênciado Object getContent() String getHeaderField(String) String getHeaderField(int) InputStream getInputStream() OutputStream getOutputStream() Campos do cabeçalho acedidos frequentemente String getContentEncoding() int getContentLength() String getContentType() long getDate() long getExpiration() long getLastModified() Nuno Valero Ribeiro Gab. F269 5-dez-18

20 Gab. F269 nribeiro@est.ips.pt
import java.net.*; import java.io.*; public class URLConnectionReader { public static void main(String[] args) throws Exception { URL yahoo = new URL(" URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } Nuno Valero Ribeiro Gab. F269 5-dez-18

21 Classe URLConnection - exemplo 2
import java.io.*; import java.net.*; public class Reverse { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse string_to_reverse"); System.exit(1); } String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL(" URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("string=" + stringToReverse); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } Nuno Valero Ribeiro Gab. F269 5-dez-18


Carregar ppt "Comunicação em Rede no JAVA"

Apresentações semelhantes


Anúncios Google