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

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

Java em Redes de Computadores

Apresentações semelhantes


Apresentação em tema: "Java em Redes de Computadores"— Transcrição da apresentação:

1 Java em Redes de Computadores
Marcos André S. Kutova Setembro/98

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

3 Introdução

4 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.

5 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 são reservadas.

6 URL - Uniform Resource Locator

7 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

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

9 URLS Outros construtores
new URL(“http”,” new URL(“ new URL(“http”,” new URL(“

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

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

12 URLS Exemplo import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL(" 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

13 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); }

14 URLS Reverse (2/3) 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(); 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.

15 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(); }

16 Sockets

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

18 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;

19 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]+"."); }

20 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();

21 SERVIDOR CHAT ChatServer

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

23 SERVIDOR CHAT ChatServer ChatServerThread

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

25 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();

26 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); }

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

28 SERVIDOR CHAT ChatServer ChatServerThread sClientGroup

29 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(); }

30 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();

31 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" */ }

32 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); }

33 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());

34 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 ; }

35 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);

36 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 ; }

37 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();

38 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 ); }

39 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 */

40 SERVIDOR CHAT ChatServer ChatServerThread sClientGroup sClientThreads

41 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; }

42 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); }

43 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;

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

45 CLIENTE CHAT ChatServer ChatClient ChatServerThread Internet
sClientGroup ChatClient sClientThreads

46 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;

47 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;

48 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) {}

49 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 );

50 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 ) {}

51 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); }

52 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 ) {

53 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(); }

54 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.");

55 Serialização

56 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

57 SERIALIZAÇÃO Marshaling Objeto writeObject() ObjectOutputStream bytes

58 SERIALIZAÇÃO Unmarshaling Objeto readObject() InputStream bytes

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

60 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( ); out.flush(); }

61 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(); = (String) in.readObject(); }

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

63 RMI - Remote Method Invocation

64 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

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

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

67 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

68 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; }

69 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 {

70 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(); }

71 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)

72 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() ); }

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

74 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”); }

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

76 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 ) }

77 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; }

78 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(); }

79 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..." ); }

80 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..." ); }

81 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 ); }

82 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 ); }

83 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()); }

84 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; }

85 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; }

86 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 ); }

87 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 );

88 CLIENTE CHAT RMI ChatClientImpl.java (4/6) // Rotina Principal
public static void main( String args[] ) { String comando = // 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] );

89 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( ) ) { // Processa o comando if (comando.equalsIgnoreCase( )) { 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 );

90 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

91 JDBC

92 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

93 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"); }

94 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

95 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

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

97 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.

98 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()

99 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();

100 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 - Black Art of Java Game Programming - J.Fan, E.Ries & C.Tenitchi


Carregar ppt "Java em Redes de Computadores"

Apresentações semelhantes


Anúncios Google