Upload
internet
View
103
Download
0
Embed Size (px)
Citation preview
Java em Redes de ComputadoresJava em Redes de Computadores
Marcos André S. [email protected]
Setembro/98
ÍNDICEÍNDICE
• Introdução
• URLs
• Sockets
• Serialização
• RMI
• JDBC
IntroduçãoIntrodução
PROTOCOLOSPROTOCOLOS
Protocolos da camada de transporte• TCP - Transport Control Protocol
Protocolo orientado à conexão que garante um fluxo de dados confiável.
• UDP - User Datagram ProtocolProtocolo não orientado à conexão que envia pacotes independentes de dados e não garante a entrega.
PORTASPORTAS
Portas• 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 LocatorURL - Uniform Resource Locator
URLSURLS
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
URLSURLS
Criando uma URL• http://www.gamelan.com
• URL gamelan = new URL(“http://www.gamelan.com/”);
Criando uma URL relativa• URL gamelan = new URL(“http://www.gamelan.com/”);
• URL gamelanGames = new
URL(gamelan,“pages/games.html”);
• URL gamelanPuzzle = new URL(gamelanGames,“#PUZZLE”);
URLSURLS
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”);
URLSURLS
Exceção• MalformedURLException
• try { URL myURL = new URL( ... );} catch (MalformedURLException e ) { ... // código para tratar a exceção ...}
URLSURLS
Métodos• getProtocol();
• getHost();
• getPort();
• getFile();
• getRef();
URLSURLS
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(); }}
URLSURLS
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);
}
URLSURLS
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();
URLSURLS
Reverse (3/3)
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
SocketsSockets
SOCKETSSOCKETS
O que é um Socket?• Socket é uma ponta de uma comunicação ponto-a-ponto
entre dois programas rodando em uma rede.
SOCKETSSOCKETS
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;
SOCKETSSOCKETS
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]+".");
System.exit(1);
}
SOCKETSSOCKETS
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 CHATSERVIDOR CHAT
ChatServer
SERVIDOR CHATSERVIDOR CHAT
ChatServer
import ChatServerThread;
class ChatServer {
public static void main(String args[]) {
new ChatServerThread().start();
}
}
SERVIDOR CHATSERVIDOR CHAT
ChatServer
ChatServerThread
SERVIDOR CHATSERVIDOR CHAT
ChatServerThread (1/4)
import java.net.*;
import java.lang.*;
import sClientGroup;
public class ChatServerThread extends Thread {
ServerSocket servSock = null;
sClientGroup group;
SERVIDOR CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR CHAT
ChatServerThread (4/4)
public void finalize() {
try {
servSock.close();
} catch(Exception e) {}
servSock = null;
group.stop();
}
}
SERVIDOR CHATSERVIDOR CHAT
ChatServer
ChatServerThread
sClientGroup
SERVIDOR CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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); return ; }
SERVIDOR CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR 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 CHATSERVIDOR CHAT
ChatServer
ChatServerThread
sClientGroup
sClientThreads
SERVIDOR CHATSERVIDOR 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 CHATSERVIDOR 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; try { input = dis.readLine().trim(); if(input != null) parent.handleInput(input, this); } catch (Exception e) {} } }
SERVIDOR CHATSERVIDOR 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() { try { ps.close(); dis.close(); theSock.close(); } catch(Exception e) {} theSock = null; }
SERVIDOR CHATSERVIDOR CHAT
sClientThread (4/4)
public void setAlias(String str) {
alias = str;
}
public String getAlias() {
return alias;
}
}
CLIENTE CHATCLIENTE CHAT
ChatServer
sClientThreads
ChatClient
ChatClient
ChatClient
Internet
ChatServerThread
sClientGroup
CLIENTE CHATCLIENTE 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 CHATCLIENTE 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 CHATCLIENTE 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; } try { Thread.sleep( 1000 ); } catch(Exception e) {} }
CLIENTE CHATCLIENTE 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 CHATCLIENTE CHAT
ChatClient (5/9)
/* Keyboard reading */ while( !command.startsWith( "logout" ) ) { try { if( tec.ready() ) { command = tec.readLine(); try { 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 CHATCLIENTE 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 CHATCLIENTE 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 ) {
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 CHATCLIENTE 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."); } } }}
CLIENTE CHATCLIENTE CHAT
SerializaçãoSerialização
SERIALIZAÇÃOSERIALIZAÇÃO
Definição• Formatação dos dados para que possam ser enviados pela
rede.• As classes devem implementar a interface Serializable
int bytes
Internet
bytes int
Marshaling Unmarshaling
SERIALIZAÇÃOSERIALIZAÇÃO
Marshaling• writeObject()
Objeto
writeObject()
ObjectOutputStream bytes OutputStream
SERIALIZAÇÃOSERIALIZAÇÃO
Unmarshaling• readObject()
ObjetoreadObject()
ObjectInputStreambytesInputStream
SERIALIZAÇÃOSERIALIZAÇÃ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ÇÃOSERIALIZAÇÃ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ÇÃOSERIALIZAÇÃ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ÇÃOSERIALIZAÇÃO
Vantagens
• Facilidade de programação
• Persistência de objetos
Desvantagens
• Velocidade de comunicação
RMI - Remote Method InvocationRMI - Remote Method Invocation
RMIRMI
O que é RMI?• Remote Method Invocation• Permite que objetos rodando em uma JVM invoquem
métodos de objetos rodando em outra JVM.
InternetJVM 1
Método()
objeto
JVM 2
Método()
objeto
RMIRMI
Arquitetura do RMI
Internet
JVM 1
Método()
objeto
JVM 2
Método()
objeto
Stub Skeleton
RMIRMI
Serviço de Nomes
server
rmi://server/name
clientname
Naming Registry
Remote ObjectReferência Remota
Internet
SERVIDOR RMISERVIDOR 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 RMISERVIDOR 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 RMISERVIDOR RMI
Implementando a interface remota• Declarar as interfaces sendo implementadas• Definir o construtor do objeto remoto• Fornecer uma implementação para cada método remoto
declarado nas interfaces
Declaraçãopackage hello;
import java.rmi.*;
import java.rmi.server.*;
public class HelloWorldImpl extends UnicastRemoteObject implements HelloWorld {
SERVIDOR RMISERVIDOR RMI
java.rmi.server.UnicastRemoteObject• Superclasse para implementação de objetos remotos
• Comunicação ponto-a-ponto via sockets
Construtor• public HelloWorldImpl() throws RemoteException {
super();
}
SERVIDOR RMISERVIDOR RMI
Implementação dos métodos remotos• 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 RMISERVIDOR 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 RMISERVIDOR RMI
Compilando
• javac -d . *.java
Gerando stubs e skeletons
• rmic -d . hello.HelloWorldImpl
CLIENTE RMICLIENTE 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”); } }}
RMIRMI
Rodando o rmiregistry
• start rmiregistry 1099 (Windows)
ou
• rmiregistry & (UNIX)
Rodando o servidor
• java hello.HelloWorldImpl
Rodando o cliente
• java hello.HelloClient
SERVIDOR CHAT RMISERVIDOR 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()
throws java.rmi.RemoteException;public void desconecta( ChatClient c )
throws java.rmi.RemoteException;public void diga( ChatClient c, String msg )
throws java.rmi.RemoteException;}
SERVIDOR CHAT RMISERVIDOR 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 RMISERVIDOR 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 RMISERVIDOR CHAT RMI
ChatServerImpl.java (3/7)
// Conecta novo usuario a sessaopublic 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 RMISERVIDOR CHAT RMI
ChatServerImpl.java (4/7)
// Desconecta um usuariopublic 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 RMISERVIDOR CHAT RMI
ChatServerImpl.java (5/7)
// Retorna os usuarios ativospublic String [] naSessao() throws RemoteException {
// Pega os nomes dos usuariosString [] 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 RMISERVIDOR CHAT RMI
ChatServerImpl.java (6/7)
// Envia uma mensagem publicapublic void diga( ChatClient c, String msg )
throws java.rmi.RemoteException {
// Avisa a todos sobre o novo usuarioString nome = (String) usuariosRegistrados.get( c );Enumeration usuarios = usuariosRegistrados.keys();while( usuarios.hasMoreElements() ) {
ChatClient c2 = (ChatClient) usuarios.nextElement();c2.disse( nome, msg );
}}
SERVIDOR CHAT RMISERVIDOR CHAT RMI
ChatServerImpl.java (7/7)
// Rotina principalpublic 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 RMICLIENTE 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 RMICLIENTE 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 RMICLIENTE CHAT RMI
ChatClientImpl.java (2/6)
// Construtor da classe public ChatClientImpl(ChatServer servidor,String nome)
throws RemoteException {super();
// Grava o nome do usuariothis.nome = nome;
// Conecta-se ao servidorthis.servidor = servidor;servidor.conecta(nome, this );
}
CLIENTE CHAT RMICLIENTE 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 RMICLIENTE CHAT RMI
ChatClientImpl.java (4/6)
// Rotina Principalpublic 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 RMICLIENTE CHAT RMI
ChatClientImpl.java (5/6)
// Cria um fluxo de entrada do tecladoBufferedReader teclado = new BufferedReader( new InputStreamReader( System.in ) ); // Loop de troca de mensagenswhile( !comando.equalsIgnoreCase( "@sai" ) ) {
// Processa o comandoif (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 RMICLIENTE CHAT RMI
ChatClientImpl.java (6/6)
// Lê novo comando do tecladowhile( ! 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
JDBCJDBC
JDBCJDBC
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
JDBCJDBC
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");
}
JDBCJDBC
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
Client System
Data Store
JDBCJDBC
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
Client System
Application Server
Data Store
JDBCJDBC
Classe DriverManager
Carregando o driver• Class.fornName( “postgresql.Driver” );
Estabelecendo conexão• DriverManager.getConnection( url, nome, senha );
JDBCJDBC
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.
JDBCJDBC
Execução das instruções
• executeQuery()
• executeUpdate()
• execute() (retorna mais de 1 conjunto de resultados)
Resultado das instruções
• Classe ResultSet
• Métodos .next()
.getXXX()
JDBCJDBC
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 resultadosStatement select = con.createStatement();ResultSet result = select.executeQuery(
"SELECT codinome, senha FROM usuarios" );
// Testa se o usuário está cadastradoencontrou = 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ênciasReferê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