SlideShare uma empresa Scribd logo
http://publicationslist.org/junio
Rede
Prof. Jose Fernando Rodrigues Junior
http://www.icmc.usp.br/~junio
junio@icmc.usp.br
INSTITUTO DE CIÊNCIAS MATEMÁTICAS E DE COMPUTAÇÃO - USP
SCC0504 - Programação Orientada a
Objetos
http://publicationslist.org/junio
Rede – conceitos básicos
• A comunicação entre computadores é denominada comunicação via
rede de computadores
• Para que esta comunicação ocorra, os computadores participantes da
rede precisam seguir um protocolo
• Um protocolo é uma sequência de passos necessária para que os dois
computadores saibam:
• quando uma conexão começa e quando termina
• quando uma transmissão começa e quando termina
• quando ocorre uma falha, e como se recuperar da falha
• entre outras funcionalidades necessárias
http://publicationslist.org/junio
Rede – conceitos básicos - TCP
• O protocolo mais usado é o Transmission Control Protocol (TCP)
• O TCP provê a transmissão segura (garantia de entrega),
ordenada, com verificação de erro, de um stream de bytes entre
dois programas de computador, cada um em um computador diferente
• O protocolo Internet Protocol (IP) funciona de maneira
complementar ao TCP (e a outros protocolos) oferecendo
funcionalidades de roteamento entre computadores
• Segundo o IP, um computador é identificado por um número IP
• Em cada computador, processos são identificados por números
de portas
http://publicationslist.org/junio
Sockets
• Socket: trata-se de um conceito presente em diversas plataformas de
programação, o qual abstrai o uso do protocolo TCP para a
comunicação entre computadores
• Definição: uma socket é ponto terminal (endpoint = IP:port) de uma
conexão bi-direcional entre dois programas que usam a rede para se
comunicar.
• Uma socket é atrelada a um número de porta, de maneira que o
protocolo TCP possa identificar a aplicação para a qual os dados são
destinados
http://publicationslist.org/junio
Sockets
O pacote java.net provê duas classes que possibilitam o uso de sockets:
• ServerSocket: usado para receber conexões
• Socket: usado para fazer conexões
• Basicamente o uso destas classes ocorre na seguinte ordem:
1. Abertura da Socket
2. Abertura de streams de leitura e escrita na Socket
3. Escrita e leitura de dados nas/das streams
4. Fechamento dos streams
5. Fechamento da socket
• O Java abstrai as funcionalidades de rede usando implementações
específicas de cada plataforma (Windows, Mac, Linux, ...)
http://publicationslist.org/junio
Servidor TCP simples
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
Servidor
SERVIDOR
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Servidor
ServerSocket
OUVIDO
SERVIDOR
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
Servidor
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
Servidor
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR CLIENTE
ENVIA
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR CLIENTE
RECEBE
ENVIA
ENVIA
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR
ENVIA
CLIENTE
RECEBE
ENVIA
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR
ENVIA
CLIENTE
RECEBE
ENVIA
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
Servidor
ServerSocket
OUVIDO
SERVIDOR
ENVIA
CLIENTE
RECEBE
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
Servidor
ServerSocket
OUVIDO
SERVIDOR CLIENTE
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
OUVIDO.close();
Servidor
SERVIDOR CLIENTE
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
OUVIDO.close();
Servidor
SERVIDOR CLIENTE
Perceba que existe um protocolo entre o servidor e o
cliente:
• no servidor: receber, e em seguida enviar
• no cliente: enviar, e em seguida receber
Protocolos são necessários em comunicação entre
computadores, pois eles definem o quê e quando as coisas irão
acontecer.
Em todos os próximos exemplos, sempre haverá um
protocolo, por mais simples que seja.
http://publicationslist.org/junio
Cliente TCP simples
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Cliente
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
Cliente
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
ENVIA.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
ENVIA RECEBE
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
ENVIA.close();
RECEBE.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
ENVIA.close();
RECEBE.close();
LEITOR_ENTRADA_PADRAO.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Cliente que envia texto ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ENVIA = new PrintWriter(
CLIENTE_SOCKET.getOutputStream(), true);
RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader(
new InputStreamReader(System.in));
String userInput = "";
while(userInput.compareTo(“BYE") != 0){
userInput = LEITOR_ENTRADA_PADRAO.readLine();
ENVIA.println(userInput);
System.out.println(RECEBE.readLine());
}
ENVIA.close();
RECEBE.close();
LEITOR_ENTRADA_PADRAO.close();
CLIENTE_SOCKET.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
http://publicationslist.org/junio
Servidor TCP simples para múltiplos clientes usando
Threads
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
OUVIDO.close();
Servidor com Threads
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
OUVIDO.close();
Servidor com Threads
Este código se torna o run de uma
Thread.
http://publicationslist.org/junio
• Servidor que repete o que o cliente envia:
ServerSocket OUVIDO = new ServerSocket(8008);
while (bEscutando) {
Socket SERVIDOR_SOCKET = OUVIDO.accept();
EchoServerThread threadServidora = new EchoServerThread(SERVIDOR_SOCKET);
threadServidora.start();
}
OUVIDO.close();
Servidor com Threads
http://publicationslist.org/junio
public class EchoServerThread extends Thread {
private Socket SERVIDOR_SOCKET = null;
public EchoServerThread(Socket umCLIENTE) {
this.SERVIDOR_SOCKET = umCLIENTE;
}
public void run() {
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
}
}
Servidor com Threads
http://publicationslist.org/junio
public class EchoServerThread extends Thread {
private Socket SERVIDOR_SOCKET = null;
public EchoServerThread(Socket umCLIENTE) {
this.SERVIDOR_SOCKET = umCLIENTE;
}
public void run() {
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
SERVIDOR_SOCKET.getInputStream()));
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
String str = "";
while(str.compareTo("BYE") != 0){
str = RECEBE.readLine();
ENVIA.println("O servidor repete: "" + str + """);
ENVIA.flush();
}
RECEBE.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
}
}
Servidor com Threads
AThread recebe um socket para se
comunicar com o cliente, e passa a
ser o servidor para aquele cliente.
http://publicationslist.org/junio
Servidor TCP para objetos
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
Servidor
SERVIDOR
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Servidor
ServerSocket
OUVIDO
SERVIDOR
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
Servidor
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
Servidor
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR CLIENTE
ENVIA
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR CLIENTE
RECEBE
ENVIA
ENVIA
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Object oTemp = null;
do{
oTemp = RECEBE_OBJETO.readObject();
ENVIA.println(“Objeto recebido");
ENVIA.flush();
}while(oTemp != null);
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR
ENVIA
CLIENTE
RECEBE
ENVIA
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Object oTemp = null;
do{
oTemp = RECEBE_OBJETO.readObject();
ENVIA.println(“Objeto recebido");
ENVIA.flush();
}while(oTemp != null);
Servidor
ServerSocket
OUVIDO
RECEBE
SERVIDOR
ENVIA
CLIENTE
RECEBE
ENVIA
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Object oTemp = null;
do{
oTemp = RECEBE_OBJETO.readObject();
ENVIA.println(“Objeto recebido");
ENVIA.flush();
}while(oTemp != null);
RECEBE_OBJETO.close();
Servidor
ServerSocket
OUVIDO
SERVIDOR
ENVIA
CLIENTE
RECEBE
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Object oTemp = null;
do{
oTemp = RECEBE_OBJETO.readObject();
ENVIA.println(“Objeto recebido");
ENVIA.flush();
}while(oTemp != null);
RECEBE_OBJETO.close();
ENVIA.close();
Servidor
ServerSocket
OUVIDO
SERVIDOR CLIENTE
http://publicationslist.org/junio
• Servidor que recebe objetos do cliente:
ServerSocket OUVIDO = new ServerSocket(8008);
Socket SERVIDOR_SOCKET = OUVIDO.accept();
ObjectInputStream RECEBE_OBJETO = new ObjectInputStream(
SERVIDOR_SOCKET.getInputStream());
PrintWriter ENVIA = new PrintWriter(
new OutputStreamWriter(
SERVIDOR_SOCKET.getOutputStream()));
Object oTemp = null;
do{
oTemp = RECEBE_OBJETO.readObject();
ENVIA.println(“Objeto recebido");
ENVIA.flush();
}while(oTemp != null);
RECEBE_OBJETO.close();
ENVIA.close();
SERVIDOR_SOCKET.close();
OUVIDO.close();
Servidor
SERVIDOR CLIENTE
http://publicationslist.org/junio
Cliente TCP para objetos
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Cliente
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
Cliente
ServerSocket
OUVIDO
OUVIDO.accept( )
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
for(Object o : lista){
ENVIA_OBJETO.writeObject(o);
System.out.println(RECEBE.readLine());
}
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
for(Object o : lista){
ENVIA_OBJETO.writeObject(o);
System.out.println(RECEBE.readLine());
}
ENVIA_OBJETO.writeObject(null);
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
RECEBE
ENVIA RECEBE
ENVIA
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
for(Object o : lista){
ENVIA_OBJETO.writeObject(o);
System.out.println(RECEBE.readLine());
}
ENVIA_OBJETO.writeObject(null);
ENVIA_OBJETO.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
ENVIA RECEBE
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
for(Object o : lista){
ENVIA_OBJETO.writeObject(o);
System.out.println(RECEBE.readLine());
}
ENVIA_OBJETO.writeObject(null);
ENVIA_OBJETO.close();
RECEBE.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
Socket
http://publicationslist.org/junio
• Cliente que envia objetos ao servidor:
Socket CLIENTE_SOCKET = new Socket("localhost", 8008);
ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream(
CLIENTE_SOCKET.getOutputStream());
BufferedReader RECEBE = new BufferedReader(
new InputStreamReader(
CLIENTE_SOCKET.getInputStream()));
lista.add(new Retangulo());
lista.add(new Quadrado());
lista.add(new Triangulo());
for(Object o : lista){
ENVIA_OBJETO.writeObject(o);
System.out.println(RECEBE.readLine());
}
ENVIA_OBJETO.writeObject(null);
ENVIA_OBJETO.close();
RECEBE.close();
CLIENTE_SOCKET.close();
Cliente
ServerSocket
OUVIDO
SERVIDOR CLIENTE
http://publicationslist.org/junio
Rede – conceitos básicos - UDP
• Como vimos, o TCP provê a transmissão segura (com garantia de
entrega), ordenada, e com verificação de erro, de um stream de
bytes entre dois programas de computador, cada um em um computador
diferente
• No entanto, nem todas as aplicações tem estas necessidades, suponha,
por exemplo, uma aplicação peer-to-peer de transferência de
arquivos, como o BitTorrent
• Nesta aplicação, garantir entrega e ordem dos bytes pode
impedir seu uso, pois dificultará a gerência e a negociação de
múltiplos peers de transferência de arquivo, ao mesmo tempo em que
se recebem múltiplos arquivos – isto é, os dados não vem como
streams mas sim como torrentes (do dicionário: água rápida e impetuosa
que provém de grandes chuvas)
http://publicationslist.org/junio
Rede – conceitos básicos - UDP
• Em sistemas desta natureza são usados datagramas UDP, ao invés de
streamsTCP
• O protocolo UDP prevê a transmissão de pacotes de dados
independentes uns dos outros, sem garantia de entrega, e sem
ordem de chegada
• A API Java tem duas classes para o uso do UDP
• DatagramPacket
• DatagramSocket
http://publicationslist.org/junio
Servidor UDP simples
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
Servidor
UDP_SOCKET_SERVIDOR
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes();
UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA);
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes();
UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA);
UDP_SOCKET_SERVIDOR.send(UDP_PACOTE);
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes();
UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA);
UDP_SOCKET_SERVIDOR.send(UDP_PACOTE);
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Servidor que recebe e envia pacotes para o cliente:
DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445);
byte[] CAIXA_CORREIO = new byte[256];
DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length);
UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO);
InetAddress REMETENTE_IP = UDP_PACOTE.getAddress();
int REMETENTE_PORTA = UDP_PACOTE.getPort();
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes();
UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA);
UDP_SOCKET_SERVIDOR.send(UDP_PACOTE);
UDP_SOCKET_SERVIDOR.close();
Servidor
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
Cliente UDP simples
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
UDP_SOCKET_SERVIDOR
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
InternetInternet
UDP_SOCKET_CLIENTEUDP_SOCKET_SERVIDOR
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
InternetInternet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
InternetInternet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
InternetInternet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
byte[] A_RECEBER = new byte[256];
UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length);
UDP_SOCKET_CLIENTE.receive(UDP_PACOTE);
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
byte[] A_RECEBER = new byte[256];
UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length);
UDP_SOCKET_CLIENTE.receive(UDP_PACOTE);
System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength());
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
O poder se
consegue pela
mão esquerda,
mas se dá pela
mão direita.
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
byte[] A_RECEBER = new byte[256];
UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length);
UDP_SOCKET_CLIENTE.receive(UDP_PACOTE);
System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength());
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
http://publicationslist.org/junio
• Cliente que recebe e envia pacotes para o servidor:
byte[] A_ENVIAR = new byte[256];
A_ENVIAR = (“Me envie sabedoria”).getBytes();
DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1);
DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket();
UDP_SOCKET_CLIENTE.send(UDP_PACOTE);
byte[] A_RECEBER = new byte[256];
UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length);
UDP_SOCKET_CLIENTE.receive(UDP_PACOTE);
System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength());
UDP_SOCKET_CLIENTE.close();
Cliente
SERVIDOR
ip1:port1
CLIENTE
ip2:port2
Internet
UDP_SOCKET_SERVIDOR
Anúncio

Recomendados

Socket
Socket
Mario Jorge Pereira
 
Sockets : Introdução
Sockets : Introdução
ETEC Monsenhor Antonio Magliano
 
Socket
Socket
Baguiasri
 
Sistemas operacionais 14
Sistemas operacionais 14
Nauber Gois
 
Fundamentos de Sockets
Fundamentos de Sockets
Denis L Presciliano
 
SNMP - Rafael Rodriques
SNMP - Rafael Rodriques
marleigrolli
 
Python e Linux para a criação de ferramentas para pentest
Python e Linux para a criação de ferramentas para pentest
Edson Celio
 
9 - segurança - ataques buffer-injection
9 - segurança - ataques buffer-injection
Andre Peres
 
Dawi o protocolo-http
Dawi o protocolo-http
Carolina Espírito Santo
 
Servidor de internet (NAT, Squid, Sarg)
Servidor de internet (NAT, Squid, Sarg)
Danilo Filitto
 
Aula sockets
Aula sockets
Universidade Federal do Pampa
 
Tutorial servidor debian linux ocs invetory
Tutorial servidor debian linux ocs invetory
gigadrop
 
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago Barros, PSM
 
Atividade acl extendida
Atividade acl extendida
Arlimar Jacinto
 
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
André Déo
 
Gerência de Redes - 2.Modelo SNMP
Gerência de Redes - 2.Modelo SNMP
Mauro Tapajós
 
5 - segurança - firewall
5 - segurança - firewall
Andre Peres
 
SENAI - Segurança firewall
SENAI - Segurança firewall
Carlos Melo
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3
David Ruiz
 
Ferramentas para Detecção de Problemas em Redes
Ferramentas para Detecção de Problemas em Redes
Frederico Madeira
 
Seguranca da Informação - Filtros/tcpd
Seguranca da Informação - Filtros/tcpd
Luiz Arthur
 
1089335456 paper 4 sockets em java
1089335456 paper 4 sockets em java
josealcides2005
 
Comandos ip-de-redes-no-windows-1319-ory76a
Comandos ip-de-redes-no-windows-1319-ory76a
Ls Help Technology Suporte em TI
 
SSL no apache
SSL no apache
Carlos Eduardo
 
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Andre Peres
 
R&C 0401 07 1
R&C 0401 07 1
guest6a825195
 
Back track apresentação
Back track apresentação
Kleber Santos
 
Monitoração com Nagios
Monitoração com Nagios
Cristiano Casado
 
Histórico de Participação do Mackenzie na Maratona de Programação
Histórico de Participação do Mackenzie na Maratona de Programação
Daniel Arndt Alves
 
Apresentacao vldb
Apresentacao vldb
Universidade de São Paulo
 

Mais conteúdo relacionado

Mais procurados (20)

Dawi o protocolo-http
Dawi o protocolo-http
Carolina Espírito Santo
 
Servidor de internet (NAT, Squid, Sarg)
Servidor de internet (NAT, Squid, Sarg)
Danilo Filitto
 
Aula sockets
Aula sockets
Universidade Federal do Pampa
 
Tutorial servidor debian linux ocs invetory
Tutorial servidor debian linux ocs invetory
gigadrop
 
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago Barros, PSM
 
Atividade acl extendida
Atividade acl extendida
Arlimar Jacinto
 
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
André Déo
 
Gerência de Redes - 2.Modelo SNMP
Gerência de Redes - 2.Modelo SNMP
Mauro Tapajós
 
5 - segurança - firewall
5 - segurança - firewall
Andre Peres
 
SENAI - Segurança firewall
SENAI - Segurança firewall
Carlos Melo
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3
David Ruiz
 
Ferramentas para Detecção de Problemas em Redes
Ferramentas para Detecção de Problemas em Redes
Frederico Madeira
 
Seguranca da Informação - Filtros/tcpd
Seguranca da Informação - Filtros/tcpd
Luiz Arthur
 
1089335456 paper 4 sockets em java
1089335456 paper 4 sockets em java
josealcides2005
 
Comandos ip-de-redes-no-windows-1319-ory76a
Comandos ip-de-redes-no-windows-1319-ory76a
Ls Help Technology Suporte em TI
 
SSL no apache
SSL no apache
Carlos Eduardo
 
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Andre Peres
 
R&C 0401 07 1
R&C 0401 07 1
guest6a825195
 
Back track apresentação
Back track apresentação
Kleber Santos
 
Monitoração com Nagios
Monitoração com Nagios
Cristiano Casado
 
Servidor de internet (NAT, Squid, Sarg)
Servidor de internet (NAT, Squid, Sarg)
Danilo Filitto
 
Tutorial servidor debian linux ocs invetory
Tutorial servidor debian linux ocs invetory
gigadrop
 
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago silva barros_1102133_ads_640_servidores_de_leitura_e_envio_de_e-mails
Thiago Barros, PSM
 
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
Zabbix e SNMP - Zabbix Conference LatAm - André Déo
André Déo
 
Gerência de Redes - 2.Modelo SNMP
Gerência de Redes - 2.Modelo SNMP
Mauro Tapajós
 
5 - segurança - firewall
5 - segurança - firewall
Andre Peres
 
SENAI - Segurança firewall
SENAI - Segurança firewall
Carlos Melo
 
Web 2.0 e AJAX - Parte 2 / 3
Web 2.0 e AJAX - Parte 2 / 3
David Ruiz
 
Ferramentas para Detecção de Problemas em Redes
Ferramentas para Detecção de Problemas em Redes
Frederico Madeira
 
Seguranca da Informação - Filtros/tcpd
Seguranca da Informação - Filtros/tcpd
Luiz Arthur
 
1089335456 paper 4 sockets em java
1089335456 paper 4 sockets em java
josealcides2005
 
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Introdução a Redes de Computadores - 9 - Nível de Rede - IP (p2)
Andre Peres
 
Back track apresentação
Back track apresentação
Kleber Santos
 

Destaque (20)

Histórico de Participação do Mackenzie na Maratona de Programação
Histórico de Participação do Mackenzie na Maratona de Programação
Daniel Arndt Alves
 
Apresentacao vldb
Apresentacao vldb
Universidade de São Paulo
 
Java Swing
Java Swing
Daniel Arndt Alves
 
Hierarchical visual filtering pragmatic and epistemic actions for database vi...
Hierarchical visual filtering pragmatic and epistemic actions for database vi...
Universidade de São Paulo
 
Graph-based Relational Data Visualization
Graph-based Relational Data Visualization
Universidade de São Paulo
 
SuperGraph visualization
SuperGraph visualization
Universidade de São Paulo
 
Techniques for effective and efficient fire detection from social media images
Techniques for effective and efficient fire detection from social media images
Universidade de São Paulo
 
StructMatrix: large-scale visualization of graphs by means of structure detec...
StructMatrix: large-scale visualization of graphs by means of structure detec...
Universidade de São Paulo
 
Metric s plat - a platform for quick development testing and visualization of...
Metric s plat - a platform for quick development testing and visualization of...
Universidade de São Paulo
 
Java generics-basics
Java generics-basics
Universidade de São Paulo
 
Bubble Sort
Bubble Sort
Daniel Arndt Alves
 
Insertion Sort
Insertion Sort
Daniel Arndt Alves
 
Frequency plot and relevance plot to enhance visual data exploration
Frequency plot and relevance plot to enhance visual data exploration
Universidade de São Paulo
 
Java collections-basic
Java collections-basic
Universidade de São Paulo
 
Polimorfismo
Polimorfismo
Daniel Arndt Alves
 
Multimodal graph-based analysis over the DBLP repository: critical discoverie...
Multimodal graph-based analysis over the DBLP repository: critical discoverie...
Universidade de São Paulo
 
Dawarehouse e OLAP
Dawarehouse e OLAP
Universidade de São Paulo
 
An introduction to MongoDB
An introduction to MongoDB
Universidade de São Paulo
 
Sessao
Sessao
Daniel Arndt Alves
 
Análise de Algoritmos
Análise de Algoritmos
Daniel Arndt Alves
 
Histórico de Participação do Mackenzie na Maratona de Programação
Histórico de Participação do Mackenzie na Maratona de Programação
Daniel Arndt Alves
 
Hierarchical visual filtering pragmatic and epistemic actions for database vi...
Hierarchical visual filtering pragmatic and epistemic actions for database vi...
Universidade de São Paulo
 
Techniques for effective and efficient fire detection from social media images
Techniques for effective and efficient fire detection from social media images
Universidade de São Paulo
 
StructMatrix: large-scale visualization of graphs by means of structure detec...
StructMatrix: large-scale visualization of graphs by means of structure detec...
Universidade de São Paulo
 
Metric s plat - a platform for quick development testing and visualization of...
Metric s plat - a platform for quick development testing and visualization of...
Universidade de São Paulo
 
Frequency plot and relevance plot to enhance visual data exploration
Frequency plot and relevance plot to enhance visual data exploration
Universidade de São Paulo
 
Multimodal graph-based analysis over the DBLP repository: critical discoverie...
Multimodal graph-based analysis over the DBLP repository: critical discoverie...
Universidade de São Paulo
 
Anúncio

Semelhante a Java network-sockets-etc (20)

Sockets java
Sockets java
Thiago Matos
 
Implementação de Sockets em JAVA
Implementação de Sockets em JAVA
Marcio Palheta
 
Tecnologia java para sockets
Tecnologia java para sockets
lucascsoliveira
 
11 sockets
11 sockets
Thiago Oliveira
 
Mini-Curso de Sockets no Unipê
Mini-Curso de Sockets no Unipê
Elenilson Vieira
 
Sistemas Distribuídos - Aula 05
Sistemas Distribuídos - Aula 05
Arthur Emanuel
 
Lab 06 ping_com_udp
Lab 06 ping_com_udp
Almeida Martins
 
Fundamentos de Sockets
Fundamentos de Sockets
Denis L Presciliano
 
Sistemas Distribuídos - Comunicação Distribuída - Socket
Sistemas Distribuídos - Comunicação Distribuída - Socket
Adriano Teixeira de Souza
 
Samba, Squid, FTP, DHCP1
Samba, Squid, FTP, DHCP1
SoftD Abreu
 
Camada de aplicação parte1
Camada de aplicação parte1
Universidade Federal do Pampa
 
Sd04 (si) comunicação em sd
Sd04 (si) comunicação em sd
Computação Depressão
 
44 sockets[1]
44 sockets[1]
tomasgongacalunga
 
Prog web 00-modelo-cliente_servidor_web
Prog web 00-modelo-cliente_servidor_web
Regis Magalhães
 
Prog web 00-modelo-cliente_servidor_web
Prog web 00-modelo-cliente_servidor_web
Regis Magalhães
 
Canais Assíncronos I
Canais Assíncronos I
Heron Carvalho
 
Java recursos avançados - socket connection
Java recursos avançados - socket connection
Armando Daniel
 
Cap 02.pdf
Cap 02.pdf
MateusHonorato8
 
Workshop sobre programação em C usando a API Berkeley Sockets - Carlos A. M. ...
Workshop sobre programação em C usando a API Berkeley Sockets - Carlos A. M. ...
Tchelinux
 
Introdução a Redes de Computadores - 8 - Nível de Transporte - Sockets
Introdução a Redes de Computadores - 8 - Nível de Transporte - Sockets
Andre Peres
 
Implementação de Sockets em JAVA
Implementação de Sockets em JAVA
Marcio Palheta
 
Tecnologia java para sockets
Tecnologia java para sockets
lucascsoliveira
 
Mini-Curso de Sockets no Unipê
Mini-Curso de Sockets no Unipê
Elenilson Vieira
 
Sistemas Distribuídos - Aula 05
Sistemas Distribuídos - Aula 05
Arthur Emanuel
 
Sistemas Distribuídos - Comunicação Distribuída - Socket
Sistemas Distribuídos - Comunicação Distribuída - Socket
Adriano Teixeira de Souza
 
Samba, Squid, FTP, DHCP1
Samba, Squid, FTP, DHCP1
SoftD Abreu
 
Prog web 00-modelo-cliente_servidor_web
Prog web 00-modelo-cliente_servidor_web
Regis Magalhães
 
Prog web 00-modelo-cliente_servidor_web
Prog web 00-modelo-cliente_servidor_web
Regis Magalhães
 
Java recursos avançados - socket connection
Java recursos avançados - socket connection
Armando Daniel
 
Workshop sobre programação em C usando a API Berkeley Sockets - Carlos A. M. ...
Workshop sobre programação em C usando a API Berkeley Sockets - Carlos A. M. ...
Tchelinux
 
Introdução a Redes de Computadores - 8 - Nível de Transporte - Sockets
Introdução a Redes de Computadores - 8 - Nível de Transporte - Sockets
Andre Peres
 
Anúncio

Mais de Universidade de São Paulo (17)

A gentle introduction to Deep Learning
A gentle introduction to Deep Learning
Universidade de São Paulo
 
Computação: carreira e mercado de trabalho
Computação: carreira e mercado de trabalho
Universidade de São Paulo
 
Introdução às ferramentas de Business Intelligence do ecossistema Hadoop
Introdução às ferramentas de Business Intelligence do ecossistema Hadoop
Universidade de São Paulo
 
On the Support of a Similarity-Enabled Relational Database Management System ...
On the Support of a Similarity-Enabled Relational Database Management System ...
Universidade de São Paulo
 
Effective and Unsupervised Fractal-based Feature Selection for Very Large Dat...
Effective and Unsupervised Fractal-based Feature Selection for Very Large Dat...
Universidade de São Paulo
 
Fire Detection on Unconstrained Videos Using Color-Aware Spatial Modeling and...
Fire Detection on Unconstrained Videos Using Color-Aware Spatial Modeling and...
Universidade de São Paulo
 
Unveiling smoke in social images with the SmokeBlock approach
Unveiling smoke in social images with the SmokeBlock approach
Universidade de São Paulo
 
Vertex Centric Asynchronous Belief Propagation Algorithm for Large-Scale Graphs
Vertex Centric Asynchronous Belief Propagation Algorithm for Large-Scale Graphs
Universidade de São Paulo
 
Fast Billion-scale Graph Computation Using a Bimodal Block Processing Model
Fast Billion-scale Graph Computation Using a Bimodal Block Processing Model
Universidade de São Paulo
 
Supervised-Learning Link Recommendation in the DBLP co-authoring network
Supervised-Learning Link Recommendation in the DBLP co-authoring network
Universidade de São Paulo
 
Reviewing Data Visualization: an Analytical Taxonomical Study
Reviewing Data Visualization: an Analytical Taxonomical Study
Universidade de São Paulo
 
Complexidade de Algoritmos, Notação assintótica, Algoritmos polinomiais e in...
Complexidade de Algoritmos, Notação assintótica, Algoritmos polinomiais e in...
Universidade de São Paulo
 
Visualization tree multiple linked analytical decisions
Visualization tree multiple linked analytical decisions
Universidade de São Paulo
 
Java streams
Java streams
Universidade de São Paulo
 
Infovis tutorial
Infovis tutorial
Universidade de São Paulo
 
Java platform
Java platform
Universidade de São Paulo
 
6 7-metodologia depesquisaemcienciadacomputacao-escritadeartigocientifico-plagio
6 7-metodologia depesquisaemcienciadacomputacao-escritadeartigocientifico-plagio
Universidade de São Paulo
 
Introdução às ferramentas de Business Intelligence do ecossistema Hadoop
Introdução às ferramentas de Business Intelligence do ecossistema Hadoop
Universidade de São Paulo
 
On the Support of a Similarity-Enabled Relational Database Management System ...
On the Support of a Similarity-Enabled Relational Database Management System ...
Universidade de São Paulo
 
Effective and Unsupervised Fractal-based Feature Selection for Very Large Dat...
Effective and Unsupervised Fractal-based Feature Selection for Very Large Dat...
Universidade de São Paulo
 
Fire Detection on Unconstrained Videos Using Color-Aware Spatial Modeling and...
Fire Detection on Unconstrained Videos Using Color-Aware Spatial Modeling and...
Universidade de São Paulo
 
Unveiling smoke in social images with the SmokeBlock approach
Unveiling smoke in social images with the SmokeBlock approach
Universidade de São Paulo
 
Vertex Centric Asynchronous Belief Propagation Algorithm for Large-Scale Graphs
Vertex Centric Asynchronous Belief Propagation Algorithm for Large-Scale Graphs
Universidade de São Paulo
 
Fast Billion-scale Graph Computation Using a Bimodal Block Processing Model
Fast Billion-scale Graph Computation Using a Bimodal Block Processing Model
Universidade de São Paulo
 
Supervised-Learning Link Recommendation in the DBLP co-authoring network
Supervised-Learning Link Recommendation in the DBLP co-authoring network
Universidade de São Paulo
 
Reviewing Data Visualization: an Analytical Taxonomical Study
Reviewing Data Visualization: an Analytical Taxonomical Study
Universidade de São Paulo
 
Complexidade de Algoritmos, Notação assintótica, Algoritmos polinomiais e in...
Complexidade de Algoritmos, Notação assintótica, Algoritmos polinomiais e in...
Universidade de São Paulo
 
Visualization tree multiple linked analytical decisions
Visualization tree multiple linked analytical decisions
Universidade de São Paulo
 
6 7-metodologia depesquisaemcienciadacomputacao-escritadeartigocientifico-plagio
6 7-metodologia depesquisaemcienciadacomputacao-escritadeartigocientifico-plagio
Universidade de São Paulo
 

Java network-sockets-etc

  • 1. http://publicationslist.org/junio Rede Prof. Jose Fernando Rodrigues Junior http://www.icmc.usp.br/~junio [email protected] INSTITUTO DE CIÊNCIAS MATEMÁTICAS E DE COMPUTAÇÃO - USP SCC0504 - Programação Orientada a Objetos
  • 2. http://publicationslist.org/junio Rede – conceitos básicos • A comunicação entre computadores é denominada comunicação via rede de computadores • Para que esta comunicação ocorra, os computadores participantes da rede precisam seguir um protocolo • Um protocolo é uma sequência de passos necessária para que os dois computadores saibam: • quando uma conexão começa e quando termina • quando uma transmissão começa e quando termina • quando ocorre uma falha, e como se recuperar da falha • entre outras funcionalidades necessárias
  • 3. http://publicationslist.org/junio Rede – conceitos básicos - TCP • O protocolo mais usado é o Transmission Control Protocol (TCP) • O TCP provê a transmissão segura (garantia de entrega), ordenada, com verificação de erro, de um stream de bytes entre dois programas de computador, cada um em um computador diferente • O protocolo Internet Protocol (IP) funciona de maneira complementar ao TCP (e a outros protocolos) oferecendo funcionalidades de roteamento entre computadores • Segundo o IP, um computador é identificado por um número IP • Em cada computador, processos são identificados por números de portas
  • 4. http://publicationslist.org/junio Sockets • Socket: trata-se de um conceito presente em diversas plataformas de programação, o qual abstrai o uso do protocolo TCP para a comunicação entre computadores • Definição: uma socket é ponto terminal (endpoint = IP:port) de uma conexão bi-direcional entre dois programas que usam a rede para se comunicar. • Uma socket é atrelada a um número de porta, de maneira que o protocolo TCP possa identificar a aplicação para a qual os dados são destinados
  • 5. http://publicationslist.org/junio Sockets O pacote java.net provê duas classes que possibilitam o uso de sockets: • ServerSocket: usado para receber conexões • Socket: usado para fazer conexões • Basicamente o uso destas classes ocorre na seguinte ordem: 1. Abertura da Socket 2. Abertura de streams de leitura e escrita na Socket 3. Escrita e leitura de dados nas/das streams 4. Fechamento dos streams 5. Fechamento da socket • O Java abstrai as funcionalidades de rede usando implementações específicas de cada plataforma (Windows, Mac, Linux, ...)
  • 8. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Servidor ServerSocket OUVIDO SERVIDOR
  • 9. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); Servidor ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR
  • 10. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); Servidor ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Socket
  • 11. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); Servidor ServerSocket OUVIDO RECEBE SERVIDOR CLIENTE ENVIA
  • 12. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Servidor ServerSocket OUVIDO RECEBE SERVIDOR CLIENTE RECEBE ENVIA ENVIA
  • 13. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } Servidor ServerSocket OUVIDO RECEBE SERVIDOR ENVIA CLIENTE RECEBE ENVIA
  • 14. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } Servidor ServerSocket OUVIDO RECEBE SERVIDOR ENVIA CLIENTE RECEBE ENVIA
  • 15. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); Servidor ServerSocket OUVIDO SERVIDOR ENVIA CLIENTE RECEBE
  • 16. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); Servidor ServerSocket OUVIDO SERVIDOR CLIENTE
  • 17. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); OUVIDO.close(); Servidor SERVIDOR CLIENTE
  • 18. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); OUVIDO.close(); Servidor SERVIDOR CLIENTE Perceba que existe um protocolo entre o servidor e o cliente: • no servidor: receber, e em seguida enviar • no cliente: enviar, e em seguida receber Protocolos são necessários em comunicação entre computadores, pois eles definem o quê e quando as coisas irão acontecer. Em todos os próximos exemplos, sempre haverá um protocolo, por mais simples que seja.
  • 20. http://publicationslist.org/junio • Cliente que envia texto ao servidor: ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Cliente
  • 21. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); Cliente ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Socket
  • 22. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA
  • 23. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 24. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 25. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 26. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 27. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } ENVIA.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket ENVIA RECEBE
  • 28. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } ENVIA.close(); RECEBE.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket
  • 29. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } ENVIA.close(); RECEBE.close(); LEITOR_ENTRADA_PADRAO.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket
  • 30. http://publicationslist.org/junio • Cliente que envia texto ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ENVIA = new PrintWriter( CLIENTE_SOCKET.getOutputStream(), true); RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); BufferedReader LEITOR_ENTRADA_PADRAO = new BufferedReader( new InputStreamReader(System.in)); String userInput = ""; while(userInput.compareTo(“BYE") != 0){ userInput = LEITOR_ENTRADA_PADRAO.readLine(); ENVIA.println(userInput); System.out.println(RECEBE.readLine()); } ENVIA.close(); RECEBE.close(); LEITOR_ENTRADA_PADRAO.close(); CLIENTE_SOCKET.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE
  • 32. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); OUVIDO.close(); Servidor com Threads
  • 33. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); OUVIDO.close(); Servidor com Threads Este código se torna o run de uma Thread.
  • 34. http://publicationslist.org/junio • Servidor que repete o que o cliente envia: ServerSocket OUVIDO = new ServerSocket(8008); while (bEscutando) { Socket SERVIDOR_SOCKET = OUVIDO.accept(); EchoServerThread threadServidora = new EchoServerThread(SERVIDOR_SOCKET); threadServidora.start(); } OUVIDO.close(); Servidor com Threads
  • 35. http://publicationslist.org/junio public class EchoServerThread extends Thread { private Socket SERVIDOR_SOCKET = null; public EchoServerThread(Socket umCLIENTE) { this.SERVIDOR_SOCKET = umCLIENTE; } public void run() { BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); } } Servidor com Threads
  • 36. http://publicationslist.org/junio public class EchoServerThread extends Thread { private Socket SERVIDOR_SOCKET = null; public EchoServerThread(Socket umCLIENTE) { this.SERVIDOR_SOCKET = umCLIENTE; } public void run() { BufferedReader RECEBE = new BufferedReader( new InputStreamReader( SERVIDOR_SOCKET.getInputStream())); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); String str = ""; while(str.compareTo("BYE") != 0){ str = RECEBE.readLine(); ENVIA.println("O servidor repete: "" + str + """); ENVIA.flush(); } RECEBE.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); } } Servidor com Threads AThread recebe um socket para se comunicar com o cliente, e passa a ser o servidor para aquele cliente.
  • 39. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Servidor ServerSocket OUVIDO SERVIDOR
  • 40. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); Servidor ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR
  • 41. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); Servidor ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Socket
  • 42. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); Servidor ServerSocket OUVIDO RECEBE SERVIDOR CLIENTE ENVIA
  • 43. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Servidor ServerSocket OUVIDO RECEBE SERVIDOR CLIENTE RECEBE ENVIA ENVIA
  • 44. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Object oTemp = null; do{ oTemp = RECEBE_OBJETO.readObject(); ENVIA.println(“Objeto recebido"); ENVIA.flush(); }while(oTemp != null); Servidor ServerSocket OUVIDO RECEBE SERVIDOR ENVIA CLIENTE RECEBE ENVIA
  • 45. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Object oTemp = null; do{ oTemp = RECEBE_OBJETO.readObject(); ENVIA.println(“Objeto recebido"); ENVIA.flush(); }while(oTemp != null); Servidor ServerSocket OUVIDO RECEBE SERVIDOR ENVIA CLIENTE RECEBE ENVIA
  • 46. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Object oTemp = null; do{ oTemp = RECEBE_OBJETO.readObject(); ENVIA.println(“Objeto recebido"); ENVIA.flush(); }while(oTemp != null); RECEBE_OBJETO.close(); Servidor ServerSocket OUVIDO SERVIDOR ENVIA CLIENTE RECEBE
  • 47. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Object oTemp = null; do{ oTemp = RECEBE_OBJETO.readObject(); ENVIA.println(“Objeto recebido"); ENVIA.flush(); }while(oTemp != null); RECEBE_OBJETO.close(); ENVIA.close(); Servidor ServerSocket OUVIDO SERVIDOR CLIENTE
  • 48. http://publicationslist.org/junio • Servidor que recebe objetos do cliente: ServerSocket OUVIDO = new ServerSocket(8008); Socket SERVIDOR_SOCKET = OUVIDO.accept(); ObjectInputStream RECEBE_OBJETO = new ObjectInputStream( SERVIDOR_SOCKET.getInputStream()); PrintWriter ENVIA = new PrintWriter( new OutputStreamWriter( SERVIDOR_SOCKET.getOutputStream())); Object oTemp = null; do{ oTemp = RECEBE_OBJETO.readObject(); ENVIA.println(“Objeto recebido"); ENVIA.flush(); }while(oTemp != null); RECEBE_OBJETO.close(); ENVIA.close(); SERVIDOR_SOCKET.close(); OUVIDO.close(); Servidor SERVIDOR CLIENTE
  • 50. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Cliente
  • 51. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); Cliente ServerSocket OUVIDO OUVIDO.accept( ) SERVIDOR CLIENTE Socket
  • 52. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA
  • 53. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 54. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 55. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); for(Object o : lista){ ENVIA_OBJETO.writeObject(o); System.out.println(RECEBE.readLine()); } Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 56. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); for(Object o : lista){ ENVIA_OBJETO.writeObject(o); System.out.println(RECEBE.readLine()); } ENVIA_OBJETO.writeObject(null); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket RECEBE ENVIA RECEBE ENVIA
  • 57. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); for(Object o : lista){ ENVIA_OBJETO.writeObject(o); System.out.println(RECEBE.readLine()); } ENVIA_OBJETO.writeObject(null); ENVIA_OBJETO.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket ENVIA RECEBE
  • 58. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); for(Object o : lista){ ENVIA_OBJETO.writeObject(o); System.out.println(RECEBE.readLine()); } ENVIA_OBJETO.writeObject(null); ENVIA_OBJETO.close(); RECEBE.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE Socket
  • 59. http://publicationslist.org/junio • Cliente que envia objetos ao servidor: Socket CLIENTE_SOCKET = new Socket("localhost", 8008); ObjectOutputStream ENVIA_OBJETO = new ObjectOutputStream( CLIENTE_SOCKET.getOutputStream()); BufferedReader RECEBE = new BufferedReader( new InputStreamReader( CLIENTE_SOCKET.getInputStream())); lista.add(new Retangulo()); lista.add(new Quadrado()); lista.add(new Triangulo()); for(Object o : lista){ ENVIA_OBJETO.writeObject(o); System.out.println(RECEBE.readLine()); } ENVIA_OBJETO.writeObject(null); ENVIA_OBJETO.close(); RECEBE.close(); CLIENTE_SOCKET.close(); Cliente ServerSocket OUVIDO SERVIDOR CLIENTE
  • 60. http://publicationslist.org/junio Rede – conceitos básicos - UDP • Como vimos, o TCP provê a transmissão segura (com garantia de entrega), ordenada, e com verificação de erro, de um stream de bytes entre dois programas de computador, cada um em um computador diferente • No entanto, nem todas as aplicações tem estas necessidades, suponha, por exemplo, uma aplicação peer-to-peer de transferência de arquivos, como o BitTorrent • Nesta aplicação, garantir entrega e ordem dos bytes pode impedir seu uso, pois dificultará a gerência e a negociação de múltiplos peers de transferência de arquivo, ao mesmo tempo em que se recebem múltiplos arquivos – isto é, os dados não vem como streams mas sim como torrentes (do dicionário: água rápida e impetuosa que provém de grandes chuvas)
  • 61. http://publicationslist.org/junio Rede – conceitos básicos - UDP • Em sistemas desta natureza são usados datagramas UDP, ao invés de streamsTCP • O protocolo UDP prevê a transmissão de pacotes de dados independentes uns dos outros, sem garantia de entrega, e sem ordem de chegada • A API Java tem duas classes para o uso do UDP • DatagramPacket • DatagramSocket
  • 63. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 UDP_SOCKET_CLIENTE
  • 64. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; Servidor UDP_SOCKET_SERVIDOR SERVIDOR ip1:port1 CLIENTE ip2:port2 UDP_SOCKET_CLIENTE
  • 65. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 66. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 67. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 68. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 69. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes(); UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 70. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes(); UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA); UDP_SOCKET_SERVIDOR.send(UDP_PACOTE); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 71. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes(); UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA); UDP_SOCKET_SERVIDOR.send(UDP_PACOTE); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 72. http://publicationslist.org/junio • Servidor que recebe e envia pacotes para o cliente: DatagramSocket UDP_SOCKET_SERVIDOR = new DatagramSocket(4445); byte[] CAIXA_CORREIO = new byte[256]; DatagramPacket UDP_PACOTE = new DatagramPacket(CAIXA_CORREIO, CAIXA_CORREIO.length); UDP_SOCKET_SERVIDOR.receive(CAIXA_CORREIO); InetAddress REMETENTE_IP = UDP_PACOTE.getAddress(); int REMETENTE_PORTA = UDP_PACOTE.getPort(); byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“O poder se consegue pela mão esquerda, mas se dá pela mão direita”).getBytes(); UDP_PACOTE = new DatagramPacket(A_ENVIAR,A_ENVIAR.length, REMETENTE_IP, REMETENTE_PORTA); UDP_SOCKET_SERVIDOR.send(UDP_PACOTE); UDP_SOCKET_SERVIDOR.close(); Servidor SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_CLIENTE
  • 74. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2
  • 75. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 UDP_SOCKET_SERVIDOR
  • 76. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 InternetInternet UDP_SOCKET_CLIENTEUDP_SOCKET_SERVIDOR
  • 77. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 InternetInternet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 78. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 InternetInternet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 79. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 InternetInternet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 80. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 81. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 82. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); byte[] A_RECEBER = new byte[256]; UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length); UDP_SOCKET_CLIENTE.receive(UDP_PACOTE); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 83. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); byte[] A_RECEBER = new byte[256]; UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length); UDP_SOCKET_CLIENTE.receive(UDP_PACOTE); System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength()); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE O poder se consegue pela mão esquerda, mas se dá pela mão direita.
  • 84. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); byte[] A_RECEBER = new byte[256]; UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length); UDP_SOCKET_CLIENTE.receive(UDP_PACOTE); System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength()); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR UDP_SOCKET_CLIENTE
  • 85. http://publicationslist.org/junio • Cliente que recebe e envia pacotes para o servidor: byte[] A_ENVIAR = new byte[256]; A_ENVIAR = (“Me envie sabedoria”).getBytes(); DatagramPacket UDP_PACOTE = new DatagramPacket(A_ENVIAR,IP1, PORT1); DatagramSocket UDP_SOCKET_CLIENTE = new DatagramSocket(); UDP_SOCKET_CLIENTE.send(UDP_PACOTE); byte[] A_RECEBER = new byte[256]; UDP_PACOTE = new DatagramPacket(A_RECEBER, A_RECEBER.length); UDP_SOCKET_CLIENTE.receive(UDP_PACOTE); System.out.println(new String(UDP_PACOTE.getData(),0,UDP_PACOTE.getLength()); UDP_SOCKET_CLIENTE.close(); Cliente SERVIDOR ip1:port1 CLIENTE ip2:port2 Internet UDP_SOCKET_SERVIDOR