Escolar Documentos
Profissional Documentos
Cultura Documentos
Concorrente e Distribuída
Programação em Rede
Programação em Rede
Sumário
• Aplicações distribuídas.
FILME
Aplicações Distribuídas
Cliente- Servidor Peer 2 Peer
Programação em Rede
Comunicação TCP/IP
Programação em Rede
Endereços IP
Identification of a machine on the Internet: IP (Internet Protocol), can
have two forms:
1. DNS (Domain Name System). Ex.: www.iscte.pt
2. Numerical address
• IPv4. Ex.: 123.255.28.120 (32 bits)
• IPv6. Ex.: fe80::4c4f:bfa3:a634:1f82 (128 bits)
Exemplo endereço IP
public class QuemSouEu {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Utilização: QuemSouEu NomeDaMáquina");
System.exit(1);
}
InetAddress a = InetAddress.getByName(args[0]);
System.out.println(a);
}
}
Programação em Rede
Ligação TCP
Server Socket
Cliente
Servidor
Cliente
Programação em Rede
Socket TCP
A socket represents the endpoint of a connection between two machines:
• For each connection, two sockets exist: one on each of the connected machines.
• From a socket, a program can create an InputStream and an OutputStream, which
allows the program to respectively receive and send data.
Port TCP
• Whenever one machine connects to another, it connects
on a certain port.
• Depending on the port that client tries to connect to, a
server can offer different services.
• Normally, system services are reserved for ports 1 to 1024.
A port is a logical (and not physical) concept.
• On Linux/Unix machines typically only root/admin
processes can listen on ports bellow 1024.
Programação em Rede
Input stream:
Output stream:
Programação em Rede
Streams TCP
Server Socket
out
Cliente
in in
out
Servidor
in
Cliente
out out
in
Programação em Rede
Servidor-Cliente
Servidor
– Um computador ou uma aplcação que disponibiliza um
serviço que espera pela ligação de um ou mais clientes.
Cliente
– Um computador ou aplicação que se vai ligar ao servidor.
Programação em Rede
Servidor
public class SimpleServer {
public static final int PORTO = 8080;
private BufferedReader in;
private PrintWriter out;
. . .
}
Programação em Rede
Servidor
public void startServing() throws IOException {
ServerSocket s = new ServerSocket(PORTO);
System.out.println("Lançou ServerSocket: " + s);
try {
Socket socket = s.accept();
try {
System.out.println("Conexão aceite: " + socket);
doConnections(socket);
serve();
} finally {
System.out.println("a fechar...");
socket.close();
}
} finally {
s.close();
}
}
Programação em Rede
Servidor
private void doConnections(Socket socket) throws IOException {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
}
out
Cliente
Servidor in in
out
Programação em Rede
Servidor - ECO
private void serve() throws IOException {
while (true) {
String str = in.readLine(); Servidor
if (str.equals("FIM")) in
break;
System.out.println("Eco: " + str); out
out.println(str);
}
}
Programação em Rede
Servidor-Cliente
Server sockets have to be closed by calling close() on the
socket. If sockets are not closed properly, they will remain
open for a while. This takes up system resources and
prevents new server sockets from being opened on the
same port (for a while).
Cliente
public class SimpleClient {
Cliente
public void runClient() {
try {
connectToServer();
sendMessages();
} catch (IOException e) {
// ERRO...
} finally {
System.out.println("a fechar...");
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Programação em Rede
Cliente
private void connectToServer() throws IOException {
InetAddress endereco = InetAddress.getByName(null);
System.out.println("Endereço = " + endereco);
socket = new Socket(endereco, SimpleServer.PORTO);
Cliente
private void sendMessages() throws IOException {
for (int i = 0; i < 10; i++) {
out.println("Olá " + i);
String str = in.readLine();
System.out.println(str);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
out.println("FIM");
}
Programação em Rede
Localhost
• It is possible to test the client and server programs
without a network connection.
Serialização
• Object serialization is the process of transforming the
state of an object into a sequence of bytes;
Usos da serialização
• Network: Serialization is much easier than writing
messages in special formats for each type of messages to
be passed between client and server. Just send the
common Objects back and forward.
• File I/O: You can save the state of an application to disk to
latter re-use.
• RDBMS: You can store entire objects in relational
databases as Blobs.
Programação em Rede
Serialização em Java
• Implementação da interface Serializable
• ObjectOutputStream (serealização do objecto)
• ObjectInputStream (reconstrução do objecto)
• transient
• A cache usada pelos ObjectOutputStream e
ObjectInputStream:
– Necessidade de fazer reset.
Mais informação
Java I/O Streams:
http://docs.oracle.com/javase/tutorial/essential/io/
Arquitetura Cliente-Servidor
Programação em Rede
P2PDownload
Projecto 2018-19
P2PDownload
• Neste projeto pretende-se desenvolver um
sistema de descarga de imagens distribuído.
• Devem existir utilizadores distribuídos para lançar
e servir os pedidos de ficheiros.
• O foco do trabalho é na aplicação de programação
concorrente e distribuída.
P2PDownload
Pedido de um ficheiro
?
Pedido de um ficheiro
SIM
Pedido de um ficheiro
Pedido de um ficheiro
Pedido de um ficheiro
Pedido de um ficheiro
Pedido de um ficheiro
Rede P2P
Directório
Utilizador Utilizador
Utilizador Utilizador
Directório
Rede P2P
Rede P2P
Sumário
• Aplicações distribuídas.
• Enviar mensagens
• Mecanismo de serialização.