Cliente – Suministrador: solución
Programas completos
Cliente.java:
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class Cliente {
/**
* @param args Argumentos de la línea de comando
* El primer argumento pasado, será la ruta del fichero
*/
public static void main(String[] args) {
String nombreFichero;
File archivo;
RandomAccessFile raf = null;
FileLock bloqueo = null;
int cuenta = 1;
int valor;
/*
try{
//Rediregimos salida y error estándar a un fichero
PrintStream ps = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("javalog_cliente.txt"),true)), true);
System.setOut(ps);
System.setErr(ps);
} catch(Exception e){
System.err.println("Cliente. No he podido redirigir salidas.");
}
*/
if (args.length > 0)
nombreFichero = args[0];
//Hemos recibido la ruta del fichero en la línea de comandos
else
nombreFichero = "/home/usuario/buffer.txt";
//Fichero que se utilizará por defecto
//Preparamos el acceso al fichero
archivo = new File(nombreFichero);
while (cuenta <= 10) {//leeremos 10 datos
try {
raf = new RandomAccessFile(archivo, "rwd"); //Abrimos el fichero
//***************
//Sección crítica
System.out.println("Cliente: Intenta el bloqueo");
bloqueo = raf.getChannel().lock();
System.out.println("Cliente: Entra en la sección");
if (raf.length() > 0) {
valor = raf.readInt();
System.out.println("Cliente: dato leído " + valor);
raf.setLength(0);
cuenta ++;
} else
System.out.println("Cliente: no se puede leer");
bloqueo.release();
bloqueo = null;
System.out.println("Suministrador: Sale de la sección");
//Fin sección crítica
//*******************
Thread.sleep(2000);//simulamos tiempo de procesamiento del dato
//cuenta ++;
} catch (OverlappingFileLockException e) {
System.err.println("Cliente. Error en el bloqueo del fichero.");
System.err.println(e.toString());
} catch (IOException e) {
System.err.println("Cliente. Error al acceder al fichero.");
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println("Cliente. Enterrupted Exception.");
e.printStackTrace();
} catch (Exception e) {
System.err.println("Cliente. Excepción.");
e.printStackTrace();
} finally {
try {
if (bloqueo != null) bloqueo.release();
if (raf != null) raf.close();
} catch (Exception e2) {
System.err.println("Cliente. Error al cerrar el fichero.");
System.err.println(e2.toString());
System.exit(1); //Si hay error, finalizamos
}
}
}
}
}
Suministrador.java:
import java.io.*;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
public class Suministrador {
/**
* @param args Argumentos de la línea de comando
* El primer argumento pasado, será la ruta del fichero
*/
public static void main(String[] args) {
String nombreFichero;
File archivo;
RandomAccessFile raf = null;
FileLock bloqueo = null;
int i = 1;
/*
try{
//Rediregimos salida y error estándar a un fichero
PrintStream ps = new PrintStream(
new BufferedOutputStream(new FileOutputStream(
new File("javalog_suministrador.txt"),true)), true);
System.setOut(ps);
System.setErr(ps);
} catch(Exception e){
System.err.println("Suministrador. No he podido redirigir salidas.");
}
*/
if (args.length > 0)
nombreFichero = args[0];
//Hemos recibido la ruta del fichero en la línea de comandos
else
nombreFichero = "/home/usuario/buffer.txt";
//Fichero que se utilizará por defecto
//Preparamos el acceso al fichero
archivo = new File(nombreFichero);
while (i <= 10) {//escribiremos 10 datos
try {
raf = new RandomAccessFile(archivo, "rwd"); //Abrimos el fichero
//***************
//Sección crítica
System.out.println("Suministrador: Intenta el bloqueo");
bloqueo = raf.getChannel().lock();
System.out.println("Suministrador: Entra en la sección");
if (raf.length() == 0) {
raf.writeInt(i);
System.out.println("Suministrador: dato escrito " + i);
i ++;
} else
System.out.println("Suministrador: no puede escribir");
Thread.sleep(5000);
bloqueo.release();
bloqueo = null;
System.out.println("Suministrador: Sale de la sección");
//Fin sección crítica
//*******************
Thread.sleep(3000); //Simulamos tiempo de creación del dato
} catch (OverlappingFileLockException e) {
System.err.println("Servidor. Error en el bloqueo del fichero.");
System.err.println(e.toString());
} catch (IOException e) {
System.err.println("Servidor. Error al acceder al fichero.");
System.err.println(e.toString());
} catch (InterruptedException e) {
System.err.println("Servidor. Enterrupted Exception.");
e.printStackTrace();
} catch (Exception e) {
System.err.println("Servidor. Excepción.");
e.printStackTrace();
} finally {
try {
if (bloqueo != null) bloqueo.release();
if (raf != null) raf.close();
} catch (Exception e2) {
System.err.println("Suministrador. Error al cerrar el fichero.");
System.err.println(e2.toString());
System.exit(1); //Si hay error, finalizamos
}
}
}
}
}
Abrir en una consola el cliente:
javac Cliente.java java Cliente numeros.txt
y en otra el suministrador:
javac Suministrador.java java Suministrador numeros.txt
Deja una respuesta
Lo siento, debes estar conectado para publicar un comentario.