Este documento describe el código de un cliente y servidor para transferir archivos mediante llamadas a procedimientos remotos (RPC). El cliente envía el nombre de un archivo al servidor concurrente o secuencial, el cual verifica si existe y lo transfiere de forma concurrente o secuencial respectivamente. Se muestran capturas del proceso de transferencia y resultados cuando el archivo solicitado existe o no existe en el servidor.
Ejemplo de RPC (Servidor de Archivos) enviar archivo en Java utilizando RPC
1. CREATED BY IVAN LUIS JIMENEZ
PRACTICA 1: SERVIDOR DE ARCHIVOS CON
RPC (LLAMADAS A PROCEDIMIENTOS
REMOTOS)
ALUMNO: IVAN LUIS JIMENEZ
UNIVERSIDAD AUTÓNOMA METROPOLITANA
2. 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:UsersFrancisco
AguilarDownloadsCompressedClienteEnvArchdestino" + nombreArchivo);
BufferedOutputStream out = new BufferedOutputStream(destino);
BufferedInputStream in = new BufferedInputStream(yo.getInputStream());
3. // 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:UsersFrancisco
AguilarDownloadsCompressedClienteEnvArchdestino" + nombreArchivo);
Desktop.getDesktop().open(objetofile);
} catch (IOException ex) {
System.out.println(ex);
}
}
}
4.
5. 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) {
6. 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:UsersJonyDesktopTOOLTrimestre I UAMSistemas
Distribuidos2. Servidores multiprocesos, concurrentes y
multihilosServidorEnvioArchMultihiloServidorEnvioArchMultihiloorigen" + nombre);
if (archivo.exists()) {
return true;
} else {
7. 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();
8. 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);
}
}
}
9. 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);
10. 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;
11. 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:UsersJonyDesktopTOOLTrimestre I UAMSistemas
Distribuidos2. Servidores multiprocesos, concurrentes y
multihilosServidorEnvioArchMultihiloServidorEnvioArchMultihiloorigen" + nombre);
if (archivo.exists()) {
return true;
} else {
return false;
}
}
public void run() {
try {
entradaCliente = new DataInputStream(s.getInputStream());
salidaCliente = new DataOutputStream(s.getOutputStream());
12. 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);
13. 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);
18. 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.
19.
20. Y en el servidor tenemos:
En el caso del archivo que no existe:
Muestra mensaje que no existe: