Java em Redes de Computadores

Slides:



Advertisements
Apresentações semelhantes
Sistemas Operacionais II N Aula prática Java Sockets, RPC e RMI Eduardo Bezerra.
Advertisements

I/O Carlos Bazilio Depto de Ciência e Tecnologia
Sockets Marco Antonio – marcoreis.net Arquiteto de Software Dezembro/2007.
Entrada e Saída Marco Antonio Arquiteto de Software Dezembro/2007.
Shop Notas de implementação [Exercício da Disciplina de ADAV]
Comunicação entre processos distribuídos
Sistemas Distribuídos
Tratamento de Exceções
Ir p/ primeira página Cliente/Servidor Modelo usado para construir aplicações Servidor em número de porta conhecido – Aceita requisições e executa serviços.
Chain of Responsibility
Projeto de Sistemas de Software Luana Lachtermacher
Java RMI Alcides Calsavara. Objetivos Permitir que um método de uma classe Java em execução em uma máquina virtual JVM chame um método de um objeto (instância.
Orientação a Objetos: Modificador Final para Métodos e Classes
1 Java: Tratamento de Exceções Alcides Calsavara.
Streams Java.
1 Estruturas de Controle Márcia J. N. Rodrigues Lucena Especialização em Técnicas e Ferramentas de Apoio à Decisão Departamento.
Sistemas Paralelos e Distribuídos
Ronaldo Celso Messias Correia
1 Introdução aos Sockets (Java) Tiago Semprebom DAS – Departamento de Automação e Sistemas UFSC – Universidade Federal de Santa Catarina.
Slide 1 Rede Nacional de Ensino e Pesquisa Treinamento em Gradep - julho 2005 Serviço Worb Treinamento no GRADEp Serviço Worb WorbDemo.
Servidores e Programação Web Redes de Computadores.
Implementação Do JXTA Como Protocolo De Transporte Do JacORB
Implementação Do JXTA Como Protocolo De Transporte Do JacORB
04:27 Introdução Tipos de Fluxo de Dados e de Arquivos Manipulação de Arquivos em Java Classes FileReader e FileWriter Classes FileInputStream e FileOutputStream.
Objetos Distribuídos - Programação Distribuída Orientado a Objetos Luiz Affonso Guedes.
Programação Concorrente com Thread Java
Protocolo HTTP.
FEUPDEECRedes de Computadores/ Comunicação de Dados, 4º Ano de EEC HTTP (HyperText Transfer Protocol) Abril, 98Isidro Vila Verde 1 Introdução.
Excepções e Streams em Java
Estrutura de Dados em Java
Usando Java no Oracle Por Edson Almeida Junior
Linguagens de Programação
O Mecanismo de Threads em Java 2. Criar uma classe herdeira da super classe Thread public class minhaThread extends Thread{ public class minhaThread extends.
Concorrência em Java Threads em Java.
Tipos Agregados Homogêneos e Listas
Threads, Gerenciamento de Threads Pool de Threads, Grupo de Threads Variáveis Locais à Threads.
Sincronização com Locks. Locks É um mecanismo de sincronização de processos/threads em que estas devem ser programadas de modo que seus efeitos sobre.
JAVA MULTITHREADING TECHNIQUES
Infra-Estrutura de Comunicação (IF678)
Anália Lima (alc5) Bruno Gentilini (bgda) Eduardo Souza (efs) Ivan França (ilfn) Infra-Estrutura de comunicação Aula Prática Programação de Sockets TCP.
Infra-Estrutura de Comunicação (IF678) Aula Prática 02 – CIn/UFPE Davi Duarte Denyson José Eduardo Souza Ivan França Rafael Lima.
Infra-Estrutura de Comunicação (IF678) Aula Prática 02 – CIn/UFPE Davi Duarte Cynthia Raphaella Ivan França Jéssica Barbalho Larissa Paz Paulo Fernando.
Ismael H. F. Santos - - Petrobras/CENPES 1December 2008 Module IV – Exception Handling Prof. Ismael H F Santos.
Arquitecturas de extensão do servidor HTTP CGI | ISAPI : ASP, ASP.NET Programação na Internet Secção de Programação ISEL-DEETC-LEIC Luis Falcão -
Streams –input e output
Programação com sockets
AspectJ — Programação orientada a aspectos em Java Sérgio Soares e Paulo Borba Centro de Informática Universidade Federal de Pernambuco.
Scala Bruno Barros e Rebeka Gomes
Infra-Estrutura de Comunicação (IF678) Aula Prática 02 Programação de Sockets TCP e UDP Professor: Paulo Gonçalves CIn/UFPE.
Comunicação Entre Processos Sockets - Java
Java 2D Marco Antonio. Java2D Conjunto de classes para trabalhar com gráficos e imagens. A principal classe desta API é JComponent. Com esta classe é.
Capítulo 1. static import  A importação estática pode ser utilizado quando queremos acessar métodos ou atributos estáticos de uma outra classe.  Através.
Tipos Especiais de Listas
Alisson Rafael Appio SOP aplicado em um jogo tipo de corrida usando a arquitetura cliente e servidor Alisson Rafael Appio
Java e Serviço de Transporte Vitor Brandi Junior.
Concorrência e thread Petrônio Júnior(pglj) Márcio Neves(mmn2)
Infra-Estrutura de Comunicação (IF678) Aula Prática CIn/UFPE Rafael Lucena Roberta Mota Rubens Lopes Rodolfo Santos João Pedro Cordeiro.
Implementando comunicação em JAVA via Sockets Alcides Calsavara - Leonardo R. Nunes -
Java Kickstart, day 2 Semelhanças com linguagem C.
Polimorfismo.
Estrutura de Controle em JAVA
Exceções Profa. Patrícia A. Jaques Alterada por Leandro Tonietto abr-15.
Desenvolvimento de Aplicações TCP/IP com Sockets Márcio de Sousa Dias
Requisições e Respostas HTTP Prof. Leandro Luque.
Infra-Estrutura de Comunicação (IF678) Aula Prática 02 Programação de Sockets TCP e UDP Hugo Simões Original por: Flávio.
Redes de Computadores I Prof. Mateus Raeder Universidade do Vale do Rio dos Sinos - São Leopoldo -
Socket em Java.
UNIVERSIDADE FEDERAL DE GOIÁS INSTITUTO DE INFORMÁTICA Sistemas Distribuídos Ciência da Computação 2o. Semestre / 2006 Prof. Fábio M. Costa
Comunicação em Rede no JAVA
Programação Orientada a Objetos
Transcrição da apresentação:

Java em Redes de Computadores Marcos André S. Kutova kutova@icmc.sc.usp.br Setembro/98

ÍNDICE Introdução URLs Sockets Serialização RMI JDBC

Introdução

PROTOCOLOS Protocolos da camada de transporte TCP - Transport Control Protocol Protocolo orientado à conexão que garante um fluxo de dados confiável. UDP - User Datagram Protocol Protocolo não orientado à conexão que envia pacotes independentes de dados e não garante a entrega.

As portas 0 - 1023 são reservadas. Os computadores só têm uma conexão de rede Os dados se destinam a aplicações diferentes As portas 0 - 1023 são reservadas.

URL - Uniform Resource Locator

URLS O que é URL? URL - Uniform Resource Locator String que descreve como encontrar um recurso na Internet Composto de duas partes: protocolo e nome do recurso Nome do Recurso: Máquina Nome arquivo Referência Porta

URLS Criando uma URL Criando uma URL relativa http://www.gamelan.com URL gamelan = new URL(“http://www.gamelan.com/”); Criando uma URL relativa URL gamelanGames = new URL(gamelan,“pages/games.html”); URL gamelanPuzzle = new URL(gamelanGames,“#PUZZLE”);

URLS Outros construtores new URL(“http”,”www.gamelan.com”,“pages/games.html”); new URL(“http://www.gamelan.com/pages/games.html”); new URL(“http”,”www.gamelan.com”,80,”pages/games.html”); new URL(“http://www.gamelan.com:80/pages/games.html”);

URLS Exceção MalformedURLException try { URL myURL = new URL( ... ); } catch (MalformedURLException e ) { ... // código para tratar a exceção ... }

URLS Métodos getProtocol(); getHost(); getPort(); getFile(); getRef();

URLS Exemplo import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } BufferedReader (P, C): Buffer data while reading or writing, thereby reducing the number of accesses required on the original data source. Buffered streams are typically more efficient than similar nonbuffered streams. InputStreamReader (P, C): A reader and writer pair that forms the bridge between byte streams and character streams. An InputStreamReader reads bytes from an InputStream and converts them to characters using either the default character-encoding or a character-encoding specified by name. Similarly, an OutputStreamWriter converts characters to bytes using either the default character-encoding or a character-encoding specified by name and then writes those bytes to an OutputStream. public final InputStream openStream() throws IOException

URLS Reverse (1/3) 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"); System.exit(1); }

URLS Reverse (2/3) String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL("http://java.sun.com/cgi-bin/backwards"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("string=" + stringToReverse); out.close(); URLEncoder: The ASCII characters 'a' through 'z', 'A' through 'Z', and '0' through '9' remain the same. The space character ' ' is converted into a plus sign '+'. All other characters are converted into the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the lower 8-bits of the character. URLConnection: classe abstrata que faz referência a uma conexão. doInput e doOutput indicam que a classe deseja ler e escrever, respectivamente, a conexão.

URLS Reverse (3/3) BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); }

Sockets

SOCKETS O que é um Socket? Socket é uma ponta de uma comunicação ponto-a-ponto entre dois programas rodando em uma rede.

SOCKETS Lendo e escrevendo com Sockets (1/3) 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;

SOCKETS Lendo e escrevendo com Sockets (2/3) try { echoSocket = new Socket(args[0], 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: "+args[0]+"."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for "+ "the connection to: "+args[0]+"."); }

SOCKETS Lendo e escrevendo com Sockets (3/3) 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();

SERVIDOR CHAT ChatServer

SERVIDOR CHAT ChatServer import ChatServerThread; class ChatServer { public static void main(String args[]) { new ChatServerThread().start(); }

SERVIDOR CHAT ChatServer ChatServerThread

SERVIDOR CHAT ChatServerThread (1/4) import java.net.*; import java.lang.*; import sClientGroup; public class ChatServerThread extends Thread { ServerSocket servSock = null; sClientGroup group;

SERVIDOR CHAT ChatServerThread (2/4) ChatServerThread() { try { servSock = new ServerSocket(1123); } catch (Exception e) { System.out.println("Could not initialize. Exiting."); System.exit(1); } System.out.println("Server successfully initialized. "+ "Waiting for connection..."); group = new sClientGroup(); group.start();

SERVIDOR CHAT ChatServerThread (3/4) public void run() { while(servSock != null ) { Socket tempSock; try { tempSock = servSock.accept(); System.out.println("Received New Connection."); group.addClient( tempSock ); } catch (Exception e) { System.out.println("New Connection Failure. Exiting."); System.exit(1); }

SERVIDOR CHAT ChatServerThread (4/4) public void finalize() { try { servSock.close(); } catch(Exception e) {} servSock = null; group.stop(); }

SERVIDOR CHAT ChatServer ChatServerThread sClientGroup

SERVIDOR CHAT sClientGroup (1/11) import java.net.*; import java.io.*; import java.util.*; import java.lang.*; import sClientThread; public class sClientGroup extends Thread { Vector theGroup; sClientGroup() { theGroup = new Vector(); }

SERVIDOR CHAT sClientGroup (2/11) public void addClient(Socket s) { sClientThread tempThread; tempThread = new sClientThread( s, this ); theGroup.addElement(tempThread); tempThread.start(); } public void run() { while( true ) { try{ sleep(30000); } catch (Exception e) {} cleanHouse();

SERVIDOR CHAT sClientGroup (3/11) /* send a message "msg", of type "type", to all Clients */ public void sendMessage(String msg, String type) { int x; for(x=0; x<theGroup.size(); x++) ((sClientThread)theGroup.elementAt(x)).message(type+"||"+msg); /* remember that the format for messages is "type||message" */ }

SERVIDOR CHAT sClientGroup (4/11) /* send a message "msg", of type "type", to the Client with alias "target" */ public void sendMessage(String msg, String target, String type) { int x; sClientThread tempThread; for(x=0; x<theGroup.size(); x++) { tempThread=(sClientThread)theGroup.elementAt(x); if( tempThread.getAlias().equals(target) ) tempThread.message(type+"||"+msg); }

SERVIDOR CHAT sClientGroup (5/11) /* here is where we handle any input received from a Client */ /* This method is called by sClientThread directly */ public void handleInput(String str, sClientThread T) { StringTokenizer st; /* this next line is for debugging only. You would not include it in the final product */ System.out.println("Got: "+str+" from "+T.getAlias());

SERVIDOR CHAT sClientGroup (6/11) st = new StringTokenizer( str, "||"); if(st != null ) { String cmd, val=""; cmd = st.nextToken(); if( st.hasMoreTokens() ) val = st.nextToken(); /* "login" = a new person is logging in. Set the alias, send a welcome message, and then send everyone an updated list of Client names */ if(cmd.equals("login")) { T.setAlias( val ); sendMessage(T.getAlias()+"||"+T.getAlias()+ " has entered the room.", cmd); sendMessage(calcList(), "list"); return ; }

SERVIDOR CHAT sClientGroup (7/11) /* "logout" = one of our clients is finished and wants to disconnect. Let everyone know that and then stop the connection. The garbage collection method will take care of removing them from the list. */ if(cmd.equals("logout")) { sendMessage(T.getAlias()+" has left the room.", cmd); T.setAlias( null ); T.stop(); return ; } /* someone wants to "say" something to the whole room */ if(cmd.equals("say")) { sendMessage(T.getAlias()+" says: "+ val, cmd);

SERVIDOR CHAT sClientGroup (8/11) /* someone wants to whisper something to a specific person only */ if(cmd.equals("whisper")) { sendMessage(T.getAlias()+" whispers to you:"+ val,st.nextToken(),cmd); return ; }

SERVIDOR CHAT sClientGroup (9/11) /* return a list of all currently connected users in the form "name1&name2&name3" */ public String calcList() { int x; StringBuffer buf = new StringBuffer(); String temp; for(x=0; x<theGroup.size(); x++) { temp = ((sClientThread) (theGroup.elementAt(x))).getAlias(); if(temp != null) buf.append(temp).append('&'); } if (buf.length() >0 ) buf.setLength(buf.length()-1); return buf.toString();

SERVIDOR CHAT sClientGroup (10/11) /* go through the Vector, and search for "dead" Threads (which are disconnected) and then remove them from the list */ public void cleanHouse() { int x; sClientThread tempThread; for (x=0; x<theGroup.size(); x++) { tempThread = (sClientThread)theGroup.elementAt(x); if( tempThread==null || ! tempThread.isAlive() ) theGroup.removeElement( tempThread ); }

SERVIDOR CHAT sClientGroup (11/11) public void finalize() { Thread t; for( int x=0;x<theGroup.size();x++) { t = (Thread)theGroup.elementAt(x); if( t!=null && t.isAlive() ) t.stop(); } /* END OF CLASS */

SERVIDOR CHAT ChatServer ChatServerThread sClientGroup sClientThreads

SERVIDOR CHAT sClientThread (1/4) import java.net.*; import java.lang.*; import java.io.*; import java.util.*; import sClientGroup; public class sClientThread extends Thread { sClientGroup parent; Socket theSock; BufferedReader dis; PrintWriter ps; String alias; sClientThread(Socket s, sClientGroup p) { theSock = s; parent = p; }

SERVIDOR CHAT sClientThread (2/4) public void run() { try { dis = new BufferedReader( new InputStreamReader ( theSock.getInputStream())); ps = new PrintWriter( theSock.getOutputStream()); } catch (Exception e) {} while (theSock != null) { String input = null; input = dis.readLine().trim(); if(input != null) parent.handleInput(input, this); }

SERVIDOR CHAT sClientThread (3/4) public boolean message(String str) { try { ps.println(str); os.flush() } catch (Exception e) { return false; } return true; public void finalize() { ps.close(); dis.close(); theSock.close(); } catch(Exception e) {} theSock = null;

SERVIDOR CHAT sClientThread (4/4) public void setAlias(String str) { } public String getAlias() { return alias;

CLIENTE CHAT ChatServer ChatClient ChatServerThread Internet sClientGroup ChatClient sClientThreads

CLIENTE CHAT ChatClient (1/9) import java.net.*; import java.io.*; import java.util.*; public class ChatClient implements Runnable { BufferedReader dis = null; PrintWriter ps; Thread out; String name; Socket sock;

CLIENTE CHAT ChatClient (2/9) /* main */ public static void main( String args[] ) { Socket sock = null; BufferedReader dis = null; PrintWriter ps = null; BufferedReader tec = new BufferedReader( new InputStreamReader( System.in ) ); String command = ""; String theHost = "", name = ""; int thePort = 1123;

CLIENTE CHAT ChatClient (3/9) /* setup communication with the server */ while( sock == null ) { theHost = args[0]; name = args[1]; try { sock = new Socket(theHost,thePort); dis = new BufferedReader( new InputStreamReader(sock.getInputStream())); ps = new PrintWriter( sock.getOutputStream() ); } catch (Exception e) { System.out.println("Unable to contact host. Retrying..."); sock = null; } Thread.sleep( 1000 ); } catch(Exception e) {}

CLIENTE CHAT ChatClient (4/9) /* register itself */ try { ps.println("login||"+name); ps.flush(); } catch(Exception e) { sock = null; System.out.println("Connection lost.\n"); System.exit(1); } System.out.println("Logged in to server successfully.\n"); /* Creates new client */ ChatClient c = new ChatClient( name, sock, dis, ps );

CLIENTE CHAT ChatClient (5/9) /* Keyboard reading */ while( !command.startsWith( "logout" ) ) { try { if( tec.ready() ) { command = tec.readLine(); ps.println(command); ps.flush(); } catch(Exception e) { System.out.println("Connection lost.\n"); sock = null; System.exit(1); } else Thread.sleep( 1000 ); } catch( Exception e ) {}

CLIENTE CHAT ChatClient (6/9) try { tec.close(); dis.close(); ps.close(); sock.close(); } catch (Exception e) {} sock = null; System.out.println("Logged out from server.\n"); System.exit(0); }

CLIENTE CHAT ChatClient (7/9) public ChatClient( String name, Socket sock, BufferedReader dis, PrintWriter ps ) { this.name = name; this.sock = sock; this.ps = ps; this.dis = dis; out = new Thread( this ); out.start(); } /* reads message from other clientes */ public void run() { while( sock != null ) { try { if( dis != null ) {

CLIENTE CHAT ChatClient (8/9) String str = dis.readLine(); if(str != null) { if(str.indexOf("||") != -1) { StringTokenizer st = new StringTokenizer(str,"||"); String cmd = st.nextToken(); String val = st.nextToken(); if(cmd.equals("list")) { System.out.print( "Users: " ); StringTokenizer st2 = new StringTokenizer(val, "&"); while(st2.hasMoreTokens()) System.out.print(st2.nextToken()+" "); System.out.println(); }

CLIENTE CHAT ChatClient (9/9) else if(cmd.equals("logout")) { System.out.println(val+ " has left the room."); } else if(cmd.equals("login")) { System.out.println(val+ " has entered the room."); else { System.out.println(val); } catch (IOException e) { System.out.println("Connection lost.");

Serialização

SERIALIZAÇÃO Definição int bytes Internet Marshaling Unmarshaling Formatação dos dados para que possam ser enviados pela rede. As classes devem implementar a interface Serializable int bytes Internet Marshaling Unmarshaling

SERIALIZAÇÃO Marshaling Objeto writeObject() ObjectOutputStream bytes

SERIALIZAÇÃO Unmarshaling Objeto readObject() InputStream bytes

SERIALIZAÇÃO public class FichaCadastro implements Serializable { public String nome; public String senha; public String nomeCompleto; public String instituicao; public String email; public FichaCadastro( String nome, String senha, String nomeCompleto, String instituicao, String email ) { this.nome = nome; this.senha = senha; this.nomeCompleto = nomeCompleto; this.instituicao = instituicao; this.email = email; } }

SERIALIZAÇÃO // Processo de serialização do objeto private void writeObject( java.io.ObjectOutputStream out ) throws IOException { out.writeObject( nome ); out.writeObject( senha ); out.writeObject( nomeCompleto ); out.writeObject( instituicao ); out.writeObject( email ); out.flush(); }

SERIALIZAÇÃO // Processo de deserialização do objeto private void readObject( java.io.ObjectInputStream in ) throws IOException, ClassNotFoundException { nome = (String) in.readObject(); senha = (String) in.readObject(); nomeCompleto = (String) in.readObject(); instituicao = (String) in.readObject(); email = (String) in.readObject(); }

SERIALIZAÇÃO Vantagens Desvantagens Facilidade de programação Persistência de objetos Desvantagens Velocidade de comunicação

RMI - Remote Method Invocation

RMI O que é RMI? Internet JVM 1 Método() objeto JVM 2 Remote Method Invocation Permite que objetos rodando em uma JVM invoquem métodos de objetos rodando em outra JVM. Internet JVM 1 Método() objeto JVM 2

RMI Arquitetura do RMI JVM 1 JVM 2 objeto objeto Método() Método() Internet Stub Skeleton

RMI Serviço de Nomes server Naming Registry client Internet name rmi://server/name Remote Object Referência Remota

SERVIDOR RMI Seqüência de desenvolvimento Definir a interface remota Implementar a interface remota Implementar programa que registre o objeto Gerar o stub e o skeleton usando rmic Escrever o cliente Iniciar o rmiregistry Iniciar o servidor Executar o cliente

SERVIDOR RMI Definindo a interface remota Especificar os métodos que poderão ser invocados remotamente. Os clientes utilizam as interfaces, e não as implementações. package hello; import java.rmi.Remote; import java.rmi.RemoteException; public interface HelloWorld extends Remote { String sayHello() throws RemoteException; }

SERVIDOR RMI Implementando a interface remota Declaração Declarar as interfaces sendo implementadas Definir o construtor do objeto remoto Fornecer uma implementação para cada método remoto declarado nas interfaces Declaração package hello; import java.rmi.*; import java.rmi.server.*; public class HelloWorldImpl extends UnicastRemoteObject implements HelloWorld {

SERVIDOR RMI java.rmi.server.UnicastRemoteObject Construtor Superclasse para implementação de objetos remotos Comunicação ponto-a-ponto via sockets Construtor public HelloWorldImpl() throws RemoteException { super(); }

SERVIDOR RMI Implementação dos métodos remotos Passagem de parâmetros public String sayHello() throws RemoteException { return( “Hello, World!” ); } Passagem de parâmetros Tipos primitivos (por valor) Objetos serializáveis (por valor) Objetos remotos (por referência)

SERVIDOR RMI Rotina main Instala um gerenciador de segurança Registra o objeto remoto public static void main( String args[] ) { System.setSecurityManager( new RMISecurityManager() ); try { HelloWorld hw = new HelloWorldImpl(); Naming.rebind(“HelloWorld”, hw); } catch( Exception e ) { System.out.println( “HelloWorld: “+e.getMessage() ); }

SERVIDOR RMI Compilando Gerando stubs e skeletons javac -d . *.java rmic -d . hello.HelloWorldImpl

CLIENTE RMI Escrevendo o cliente package hello; import java.rmi.*; class HelloClient { public static void main( String args[] ) { try { HelloWorld hw = (HelloWorld)Naming.lookup(“HelloWorld”); System.out.println( hw.sayHello() ); } catch( Exception e ) { System.out.println(“Error connecting the server”); }

RMI Rodando o rmiregistry Rodando o servidor Rodando o cliente start rmiregistry 1099 (Windows) ou rmiregistry & (UNIX) Rodando o servidor java hello.HelloWorldImpl Rodando o cliente java hello.HelloClient

SERVIDOR CHAT RMI ChatServer.java package chat; interface ChatServer extends java.rmi.Remote { public void conecta( String nome, ChatClient c ) throws java.rmi.RemoteException; public String [] naSessao() public void desconecta( ChatClient c ) public void diga( ChatClient c, String msg ) }

SERVIDOR CHAT RMI ChatServerImpl.java (1/7) package chat; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; import java.util.Hashtable; import java.util.Enumeration; public class ChatServerImpl extends UnicastRemoteObject implements ChatServer { Hashtable usuariosRegistrados; . . . . . . . }

SERVIDOR CHAT RMI ChatServerImpl.java (2/7) // Construtor public ChatServerImpl() throws RemoteException { // Chama o construtor da superclasse super(); // Inicializa tabela de usuarios usuariosRegistrados = new Hashtable(); }

SERVIDOR CHAT RMI ChatServerImpl.java (3/7) // Conecta novo usuario a sessao public void conecta( String nome, ChatClient c ) throws RemoteException { // Registra o usuario usuariosRegistrados.put( c, nome ); // Avisa a todos sobre o novo usuario Enumeration usuarios = usuariosRegistrados.keys(); while( usuarios.hasMoreElements() ) { ChatClient c2 = (ChatClient) usuarios.nextElement(); if( !c.equals(c2) ) c2.evento( nome + " entrou na sala..." ); }

SERVIDOR CHAT RMI ChatServerImpl.java (4/7) // Desconecta um usuario public void desconecta( ChatClient c ) throws RemoteException { // Desconecta o usuario String nome = (String) usuariosRegistrados.get( c ); usuariosRegistrados.remove( c ); // Atualiza a tela dos usuarios Enumeration usuarios = usuariosRegistrados.keys(); while( usuarios.hasMoreElements() ) { ChatClient c2 = (ChatClient) usuarios.nextElement(); c2.evento( nome + " deixou a sala..." ); }

SERVIDOR CHAT RMI ChatServerImpl.java (5/7) // Retorna os usuarios ativos public String [] naSessao() throws RemoteException { // Pega os nomes dos usuarios String [] nomes = new String[ usuariosRegistrados.size() ]; Enumeration e = usuariosRegistrados.elements(); for( int i=0; i < nomes.length; i++ ) nomes[i] = (String) e.nextElement(); return( nomes ); }

SERVIDOR CHAT RMI ChatServerImpl.java (6/7) // Envia uma mensagem publica public void diga( ChatClient c, String msg ) throws java.rmi.RemoteException { // Avisa a todos sobre o novo usuario String nome = (String) usuariosRegistrados.get( c ); Enumeration usuarios = usuariosRegistrados.keys(); while( usuarios.hasMoreElements() ) { ChatClient c2 = (ChatClient) usuarios.nextElement(); c2.disse( nome, msg ); }

SERVIDOR CHAT RMI ChatServerImpl.java (7/7) // Rotina principal public static void main(String args[]) { // Cria e instala um gerenciador de seguranca System.setSecurityManager(new RMISecurityManager() ); // Registra-se try { ChatServer servidor = new ChatServerImpl(); Naming.rebind("Chat", servidor); System.out.println("Sessao registrada” ); } catch (Exception e) { System.out.println("Sessao nao registrada”+ e.getMessage()); }

CLIENTE CHAT RMI ChatClient.java package chat; interface ChatClient extends java.rmi.Remote { public void disse( String usuario, String mensagem ) throws java.rmi.RemoteException; public void evento( String mensagem ) throws java.rmi.RemoteException; }

CLIENTE CHAT RMI ChatClientImpl.java (1/6) package chat; import java.io.*; import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class ChatClientImpl extends UnicastRemoteObject implements ChatClient { public String nome; private ChatServer servidor; ....... }

CLIENTE CHAT RMI ChatClientImpl.java (2/6) // Construtor da classe public ChatClientImpl(ChatServer servidor,String nome) throws RemoteException { super(); // Grava o nome do usuario this.nome = nome; // Conecta-se ao servidor this.servidor = servidor; servidor.conecta(nome, this ); }

CLIENTE CHAT RMI ChatClientImpl.java (3/6) // Recebe uma mensagem digitada por alguem public void disse( String usuario, String mensagem ) throws RemoteException { System.out.println( "<"+usuario+"> "+mensagem ); } // Recebe uma mensagem enviada pelo servidor public void evento( String mensagem ) throws RemoteException { System.out.println( mensagem );

CLIENTE CHAT RMI ChatClientImpl.java (4/6) // Rotina Principal public static void main( String args[] ) { String comando = "@quem"; // Linha de comando try { // Cria uma referência ao servidor final ChatServer servidor = (ChatServer) Naming.lookup( "Chat" ); // Cria novo objeto cliente final ChatClientImpl c = new ChatClientImpl( servidor,args[0] );

CLIENTE CHAT RMI ChatClientImpl.java (5/6) // Cria um fluxo de entrada do teclado BufferedReader teclado = new BufferedReader( new InputStreamReader( System.in ) ); // Loop de troca de mensagens while( !comando.equalsIgnoreCase( "@sai" ) ) { // Processa o comando if (comando.equalsIgnoreCase( "@quem" )) { String [] eles; System.out.print( "Usuarios na sessao:" ); eles = servidor.naSessao(); for( int i=0; i < eles.length; i++ ) System.out.print( " "+eles[i] ); System.out.println(); } else servidor.diga( c, comando );

CLIENTE CHAT RMI ChatClientImpl.java (6/6) // Lê novo comando do teclado while( ! teclado.ready() ) Thread.sleep( 1000 ); comando = teclado.readLine(); } // while // Abandona a sessão servidor.desconecta( c ); System.exit( 0 ); } catch (Exception e ) { System.out.println("Exceção: "+exp.getMessage()); } // try } // main

JDBC

JDBC O que é JDBC? Java Database Connectivity ? API Java para executar instruções SQL (java.sql) Retorna o resultado da pesquisa em variáveis do Java Programação simples

JDBC O que JDBC faz? Estabelece a conexão com a base de dados Envia instruções SQL Processa o resultado Connection con = DriverManager.getConnection ( "jdbc:odbc:wombat", "login", "password") Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT a, b, c FROM Table1"); while (rs.next()) { int x = getInt("a"); String s = getString("b"); float f = getFloat("c"); }

JDBC Arquitetura Cliente/Servidor de duas camadas Aplicação fala diretamente com BD. Instruções SQL são levadas para a BD e os resultados são enviados de volta para o usuário. Client System Data Store Client System

JDBC Arquitetura Cliente/Servidor de três camadas Instruções SQL são enviadas para a camada do meio e depois para a BD. A BD processa e envia resultados de volta a camada do meio. • Possibilita o controle de manutenção, acesso e alterações • Provê vantagens de performance Client System Application Server Data Store

JDBC Classe DriverManager Carregando o driver Estabelecendo conexão Class.fornName( “postgresql.Driver” ); Estabelecendo conexão DriverManager.getConnection( url, nome, senha );

JDBC Instruções SQL Statement - criada pelo método createStatement. Envia simples instruções SQL. PreparedStatement- criada pelo método prepareStatement. Usado para instruções que carregam um ou mais parâmetros como argumentos de entrada. CallableStatement - criada pelo método prepareCall. São usadas para executar SQL stored procedures - um grupo de instruções SQL nomeado como uma chamada a uma função.

JDBC Execução das instruções Resultado das instruções executeQuery() executeUpdate() execute() (retorna mais de 1 conjunto de resultados) Resultado das instruções Classe ResultSet Métodos .next() .getXXX()

JDBC Class.forName( "postgresql.Driver" ); Connection con = DriverManager.getConnection( "jdbc:postgresql://tekila.intermidia.icmsc.sc.usp.br:5432/” +”hipermidia", "kutova", "" ); // Cria o query e busca os resultados Statement select = con.createStatement(); ResultSet result = select.executeQuery( "SELECT codinome, senha FROM usuarios" ); // Testa se o usuário está cadastrado encontrou = false; while( result.next() && !encontrou ) { String name = result.getString(1).trim(); String password = result.getString(2).trim(); if((name.compareTo(nome)==0)&&(password.compareTo(senha)==0)) encontrou = true; } select.close(); con.close();

Referências Java Technology Homepage - http://java.sun.com Teach Yourself Java 1.1 in 21 Days - L. Lemay & C. Perkins Java Unleashed - Michael Morrison The Java Tutorial - Mary Campione & Kathy Walrath Thinking In Java - http://www.bruceeckel.com/javabook.html Black Art of Java Game Programming - J.Fan, E.Ries & C.Tenitchi