Ejemplo de RPC (Servidor de Archivos) enviar archivo en Java utilizando RPC

LuisHacker1 2,075 views 20 slides May 20, 2017
Slide 1
Slide 1 of 20
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20

About This Presentation

RPC (Llamadas a Procedimientos Remotos)
Enviar archivos en de una PC a otra con código Java (RPC)
RPC en Java

Link de descarga:
http://ivanovich-hacker.blogspot.com


Slide Content

CREATED BY IVAN LUIS JIMENEZ
PRACTICA 1: SERVIDOR DE ARCHIVOS CON
RPC (LLAMADAS A PROCEDIMIENTOS
REMOTOS)
ALUMNO: IVAN LUIS JIMENEZ


UNIVERSIDAD AUTÓNOMA METROPOLITANA

CODIGO CLIENTE

package clienteenvarch;
java.awt.Desktop;
import java.net.*;
import java.io.*;

public class EnviarArchivo {

/*
*atributos para manejar salida y entrada de texto
*/
BufferedReader delTeclado;
DataOutputStream alservidor;
FileInputStream entrada;
/*
*atributos para manejar entrada de archivos
*/
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
boolean respuesta = false;
int tam = 0;
String nombreArchivo = null;

//Metodo iniciar el servidor cliente
public void iniciar() {
try {
Socket yo = new Socket("172.24.98.235", 5432);

delTeclado = new BufferedReader(new InputStreamReader(System.in));
alservidor = new DataOutputStream(yo.getOutputStream());
DataInputStream delServidor = new DataInputStream(yo.getInputStream());

escribir("Teclee el nombre del archivo:");
String el = delTeclado.readLine();
alservidor.writeUTF(el);
respuesta = delServidor.readBoolean();

if (respuesta == true) {
escribir("[Servidor]" + delServidor.readUTF());
escribir("[Servidor]:" + delServidor.readUTF());
tam = delServidor.readInt();
nombreArchivo = delServidor.readUTF();
DataInputStream ois = new DataInputStream(yo.getInputStream());
FileOutputStream destino = new FileOutputStream("C: \\Users\\Francisco
Aguilar\\Downloads\\Compressed\\ClienteEnvArch\\destino\\" + nombreArchivo);
BufferedOutputStream out = new BufferedOutputStream(destino);
BufferedInputStream in = new BufferedInputStream(yo.getInputStream());

// Creamos el array de bytes para leer los datos del archivo

byte[] buffer = new byte[tam];

// Obtenemos el archivo mediante la lectura de bytes enviados
for (int i = 0; i < buffer.length; i++) {
buffer[i] = (byte) in.read();
}
// Escribimos el archivo
out.write(buffer);
escribir("Se recivio el archivo");
abrir_archivo();
//Cerramos flujos
out.flush();
out.flush();
in.close();
out.close();
yo.close();
} else {
escribir("[Servidor]" + delServidor.readUTF());
yo.close();
}
} catch (Exception e) {
System.out.println("error " + e.getMessage() + " cliente");
}
}

public static void main(String args[]) {
EnviarArchivo ea = new EnviarArchivo();
ea.iniciar();
}

public static void escribir(String txt) {
System.out.println(txt);
}

public void abrir_archivo() {

try {
//cambiar la direccion para cada computadora
File objetofile = new File("C:\\Users\\Francisco
Aguilar\\Downloads\\Compressed\\ClienteEnvArch\\destino\\" + nombreArchivo);
Desktop.getDesktop().open(objetofile);

} catch (IOException ex) {

System.out.println(ex);
}
}

}

CODIGO SERVIDOR CONCURRENTE
package demoserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Ivan Luis Jimenez
*/
public class DemoServer {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = null;
ServerSocket ss = null;
Tarea ob;
int id = 0;

try {

ss = new ServerSocket(5432);

do {
Tarea.escribir("Socket escuchando en puerto 5432");
s = ss.accept();
id++;
Tarea.escribir("\nSe conecto el cliente No." + id + " desde la IP: " +
s.getInetAddress());
Tarea.escribir("**************************************************");
//(new Tarea(s, id)).start();
ob = new Tarea(s, id);

//ob.join();
ob.start();
if (ob.isAlive() == false) {

ss.close();
}

} while (ob.isAlive());

} catch (IOException e) {
Tarea.escribir(e.getMessage() + " [servidor]");
System.exit(3);
} finally {
try {
ss.close();
} catch (IOException e) {
Tarea.escribir(e.getMessage() + " [servidor]");
System.exit(4);
}
}

}

static class Tarea extends Thread {

int id;
Socket s = null;
/*
*Atributos para manejar salida y entrada de texto
*/
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
DataInputStream entradaCliente = null;
DataOutputStream salidaCliente = null;

/*
*Atributos para manejar salida de archivos
*/
File archivo = null;
long tiempoinicio = 0;
long tiempofinal= 0;
long tiempo_total=0;
long initialTime;
private Tarea(Socket socket, int id) {
this.s = socket;
this.id = id;
}

boolean checar(String nombre) {
archivo = new File("C:\\Users\\Jony\\Desktop\\TOOL\\Trimestre I UAM\\Sistemas
Distribuidos\\2. Servidores multiprocesos, concurrentes y
multihilos\\ServidorEnvioArchMultihilo\\ServidorEnvioArchMultihilo\\origen\\" + nombre);
if (archivo.exists()) {
return true;
} else {

return false;
}
}

public void run() {


try {
entradaCliente = new DataInputStream(s.getInputStream());
salidaCliente = new DataOutputStream(s.getOutputStream());
String nombreArchivo = entradaCliente.readUTF();
if (checar(nombreArchivo) == true) {
tiempoinicio=(System.currentTimeMillis() - this.initialTime);
System.out.println("El cliente :" + id + " comienza la transferencia
EN EL TIEMPO: "
+ (System.currentTimeMillis() - this.initialTime)
+ " milisegundos");
salidaCliente.writeBoolean(true);
salidaCliente.writeUTF("SI existe el archivo:" + nombreArchivo + " en
el servidor");
salidaCliente.writeUTF("Tamaño del archivo:" + (archivo.length() /
1024) + " KB | Nombre:" + archivo.getName());
salidaCliente.writeInt((int) archivo.length());
salidaCliente.writeUTF(nombreArchivo);
escribir("Enviando archivo:" + nombreArchivo + " a " +
s.getInetAddress());
FileInputStream entrada = new FileInputStream(archivo);
BufferedInputStream leerArch = new BufferedInputStream(entrada);
// Creamos el flujo de salida
BufferedOutputStream salida = new
BufferedOutputStream(s.getOutputStream());
// Creamos un array de tipo byte
byte[] arreglo = new byte[(int) archivo.length()];
// Leemos el archivo y lo introducimos en el array de b ytes
leerArch.read(arreglo);
// Realizamos el envio de los bytes que conforman el archivo

for (int i = 0; i < arreglo.length; i++) {
salida.write(arreglo[i]);
}
tiempofinal=(System.currentTimeMillis() - this.initialTime);
tiempo_total=tiempofinal-tiempoinicio;
escribir("Archivo Enviado a cliente:" + id);

System.out.println("El servidor termino con cliente" + id + " EN UN
TIEMPO DE: "
+ tiempo_total + " milisegundos");
System.out.println("Tiempo del cliente "+id +":
("+(System.currentTimeMillis() - this.initialTime)+") milisegundos");

salida.flush();

salida.flush();
salida.close();
entrada.close();

//escribir("Tiempo de envio:"+"("+(t0-t1)+")"+" milisegundos");
}

if (checar(nombreArchivo) == false) {
salidaCliente.writeBoolean(false);
salidaCliente.writeUTF("NO existe el archivo:" + nombreArchivo + " en
el servidor");
escribir("se envio respuesta al cliente");
}
} catch (Exception ex) {
escribir(ex.getMessage() + " id:" + id);
} finally {
try {
if (oos != null) {
oos.close();
}
if (ois != null) {
ois.close();
}
if (s != null) {
s.close();
}
System.out.println("Termino proceso para cliente: " + id);

} catch (Exception e) {
System.out.println(e.getMessage() + " [servidor]");
}
}
}

public static void escribir(String txt) {
System.out.println(txt);
}
}

}

CODIGO SERVIDOR SECUENCIAL
package demoserver;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
*
* @author Ivan Luis Jimenez
*/
public class DemoServer {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = null;
ServerSocket ss = null;
Tarea ob;
int id = 0;

try {

ss = new ServerSocket(5432);

while(true){

Tarea.escribir("Socket escuchando en puerto 5432");
s = ss.accept();
id++;
Tarea.escribir("\nSe conecto el cliente No." + id + " desde la IP: " +
s.getInetAddress());
Tarea.escribir("**************************************************");
//(new Tarea(s, id)).start();
ob = new Tarea(s, id);

//ob.join();
ob.start();
ob.join();

}

} catch (IOException e) {
Tarea.escribir(e.getMessage() + " [servidor]");
System.exit(3);
} finally {
}

}

static class Tarea extends Thread {

int id;
Socket s = null;
/*
*Atributos para manejar salida y entrada de texto
*/
ObjectInputStream ois = null;

ObjectOutputStream oos = null;
DataInputStream entradaCliente = null;
DataOutputStream salidaCliente = null;

/*
*Atributos para manejar salida de archivos
*/
File archivo = null;
long tiempoinicio = 0;
long tiempofinal= 0;
long tiempo_total=0;
long initialTime;
private Tarea(Socket socket, int id) {
this.s = socket;
this.id = id;
}

boolean checar(String nombre) {
archivo = new File("C:\\Users\\Jony\\Desktop\\TOOL\\Trimestre I UAM\\Sistemas
Distribuidos\\2. Servidores multiprocesos, concurrentes y
multihilos\\ServidorEnvioArchMultihilo\\ServidorEnvioArchMultihilo\\origen\\" + nombre);
if (archivo.exists()) {
return true;
} else {
return false;
}
}

public void run() {


try {
entradaCliente = new DataInputStream(s.getInputStream());
salidaCliente = new DataOutputStream(s.getOutputStream());

String nombreArchivo = entradaCliente.readUTF();
if (checar(nombreArchivo) == true) {
tiempoinicio=(System.currentTimeMillis() - this.initialTime);
System.out.println("El cliente :" + id + " comienza la transferencia
EN EL TIEMPO: "
+ (System.currentTimeMillis() - this.initialTime)
+ " milisegundos");
salidaCliente.writeBoolean(true);
salidaCliente.writeUTF("SI existe el archivo:" + nombreArchivo + " en
el servidor");
salidaCliente.writeUTF("Tamaño del archivo:" + (archivo.length() /
1024) + " KB | Nombre:" + archivo.getName());
salidaCliente.writeInt((int) archivo.length());
salidaCliente.writeUTF(nombreArchivo);
escribir("Enviando archivo:" + nombreArchivo + " a " +
s.getInetAddress());
FileInputStream entrada = new FileInputStream(archivo);
BufferedInputStream leerArch = new BufferedInputStream(entrada);
// Creamos el flujo de salida
BufferedOutputStream salida = new
BufferedOutputStream(s.getOutputStream());
// Creamos un array de tipo byte
byte[] arreglo = new byte[(int) archivo.length()];
// Leemos el archivo y lo introducimos en el array de bytes
leerArch.read(arreglo);
// Realizamos el envio de los bytes que conforman el archivo

for (int i = 0; i < arreglo.length; i++) {
salida.write(arreglo[i]);
}
tiempofinal=(System.currentTimeMillis() - this.initialTime);
tiempo_total=tiempofinal-tiempoinicio;
escribir("Archivo Enviado a cliente:" + id);

System.out.println("El servidor termino con cliente" + id + " EN UN
TIEMPO DE: "
+ tiempo_total + " milisegundos");
System.out.println("Tiempo del cliente "+id +":
("+(System.currentTimeMillis() - this.initialTime)+") milisegundos");

salida.flush();
salida.flush();
salida.close();
entrada.close();

//escribir("Tiempo de envio:"+"("+(t0-t1)+")"+" milisegundos");
}

if (checar(nombreArchivo) == false) {
salidaCliente.writeBoolean(false);
salidaCliente.writeUTF("NO existe el archivo:" + nombreArchivo + " en
el servidor");
escribir("se envio respuesta al cliente");
}
} catch (Exception ex) {
escribir(ex.getMessage() + " id:" + id);
} finally {
try {
if (oos != null) {
oos.close();
}
if (ois != null) {
ois.close();
}
if (s != null) {
s.close();
}
System.out.println("Termino proceso para cliente: " + id);

} catch (Exception e) {
System.out.println(e.getMessage() + " [servidor]");
}
}
}

public static void escribir(String txt) {
System.out.println(txt);
}
}

}

Capturas Cliente-Servidor concurrente
1. Ejecutando cliente (el servidor ya ha sido iniciado)


2. Ejecución y escritura del

3. Se inician los procesos en paralelo

4. Se recibieron todos los archivos a la carpeta destino

Capturas Cliente-Servidor secuencial
1. Ejecución de los cliente (ya ha sido iniciado el servidor)


2. Escribimos el nombre del archivo a solicitar, escribimos uno que no existe, y
veremos el resultado. Se enviara el archivo uno tras otro.

Y en el servidor tenemos:


En el caso del archivo que no existe:
Muestra mensaje que no existe: