Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

2021-12-17 2P Pr1 Solucion

Descargar como pdf o txt
Descargar como pdf o txt
Está en la página 1de 8

ETSISI – UPM Departamento de Sistemas Informáticos

Sistemas Distribuidos Segundo parcial de prácticas. 60 m. 17 diciembre 2020

Un estudiante quiere desarrollar una aplicación “RemoteFileService” para la transferencia fiable de


ficheros de caracteres entre dos nodos remotos. Entre otras utilidades, este servicio le permitirá
hacer copias de respaldo (backups) de ficheros de código fuente desde el directorio de Eclipse de su
portátil o un equipo del laboratorio de la ETSISI a un directorio del ordenador de su casa.
El servicio “RemoteFileService” presentará un modelo de interacción de tipo cliente/servidor, usará
sockets de tipo TCP y estará escrito en Java. El servidor escuchará en la dirección IP “MyHomeIP” y
en el puerto “RemoteFileServicePort” (por ejemplo 9999). Una vez que el cliente se conecte al
servidor, el cliente envía la siguiente información:

Nombre fichero contenido del fichero de texto

Por ejemplo, si se quiere copiar el fichero "PractEcho.java” al ordenador remoto, el cliente primero
se conecta al servidor, luego le envía el string del nombre del fichero "PractEcho.java" y finalmente el
contenido del fichero "PractEcho.java”. Por su parte, el servidor que soporta el servicio
“RemoteFileService”, tras la aceptación de la conexión, lee el nombre del fichero remoto, lo crea, si
no existe, y escribe en él el contenido que va leyendo hasta alcanzar el fin de fichero.

El estudiante tiene parte del código del cliente y servidor escritos, como se muestra a continuación.

Cliente
public class FileServiceClient {

String fileServiceHost = null;


int fileServicePort = -1;

public FileServiceClient(String fileServiceHost, int fileServicePort) {


this.fileServiceHost = fileServiceHost;
this.fileServicePort = fileServicePort;
}

public void remoteCopy(String fileName)


throws UnknownHostException, FileNotFoundException {
// 1.Pendiente de implementar

public static void main(String[] args) {


FileServiceClient myFileService =
new FileServiceClient("MyHomeIP",RemoteFileServicePort);


myFileService.remoteCopy("PractEcho.java");


}
}
Servidor

public class FileService {

Socket usrConnection = null;

public FileService(Socket usrConnection) {


this.usrConnection = usrConnection;
}

public void remoteCopy() {


// 2. Pendiente de implementar
}

public class MonothreadFileServer {// se ejecuta indefinidamente

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = null;


Socket usrConnection = null;
FileService fileService = null;

// 3. Pendiente de implementar
// Crea un socket de servidor y espera una nueva conexión
// Por cada nueva conexión recibida, crea un objeto de FileService
// invoca el método remoteCopy de dicho objeto
// cierra recursos y vuelta a esperar conexión
}
}

SE PIDE:
1. Implemente los tres métodos marcados en el código anterior como pendientes de implementar
para que se realice la copia lo más rápido posible. Trate las excepciones donde corresponda.
Use únicamente las clases de entrada/salida que se proporcionan.
2. Se desea transformar el servidor anterior en un servidor multihilo. Reescriba el método main
del servidor que figura a continuación para que cree un thread por conexión. Complete la clase
FileService añadiendo solo lo que considere oportuno. Cree threads únicamente
implementando la interfaz Runnable. Otras opciones no puntúan.

public class MultithreadFileServer {// se ejecuta indefinidamente

public static void main (String [] args) throws IOException {


// 4. pendiente de implementar
// Starting the service using threads
}

Public class FileService {


//5. Pendiente de implementar

Socket usrConnection = null;

public FileService(Socket usrConnection) {


this.usrConnection = usrConnection;
}

public void remoteCopy(Socket usrConnection) {


// Mismo contenido que en la versión monohilo. No hay que repertirlo.
}

}
Métodos más usuales para entrada/salida orientada a caracteres

java.io.InputStreamReader and java.io.OutputStreamWriter

InputStreamReader(InputStream in)
Creates a bridge from byte streams to character streams InputStreamReader.
OutputStreamWriter(OutputStream out)
Creates a bridge from character streams to byte streams OutputStreamWriter.

java.io.FileReader and java.io.FileWriter

public FileReader(String fileName) throws FileNotFoundException


Creates a new FileReader for reading character files, given the FileName to read
from.

public FileWriter(String fileName) throws IOException


Creates a new FileWriter for writing streams of characters to the file fileName.
The File is created if it does not exist.

java.io.BufferedReader and java.io.BufferedWriter

BufferedReader(Reader in)
Reads text from a character-input stream, buffering characters so as to provide
for the efficient reading of characters, arrays, and lines.

public String readLine() throws IOException


Reads a line of text. A line is considered to be terminated by any one of a line
feed ('\n') and a carriage return ('\r'), or a carriage return followed
immediately by a linefeed.

public BufferedWriter(Writer out)


Writes characters in buffer size of 8192 bytes before writing them to a
character-output stream.

void write(String s)
Writes a String.

public void newLine() throws IOException


Writes a line separator defined by the Operating system. It is not necessarily a
('\n') character.

public void flush() throws IOException


Flushes the stream. Write all characters in the buffer immediately to their
intended destination. This flush () invocation will flush all the buffers in a
chain of Writers and OutputStreams. Flushing the stream guarantees that bytes
previously written to the stream are passed to the operating system for writing.

Java.io.PrintWriter

public PrintWriter(OutputStream out,boolean autoFlush)


Creates a new PrintWriter from an existing OutputStream, which will convert
characters into bytes using the default character encoding.
If autoFlush is true, the println, printf, or format methods will flush the output
buffer.

public void println(String x)


Prints a String and then terminates the line with a line separator defined by the
Operating system. This method behaves as though it invokes print(String) and
then println().

Sockets

public ServerSocket(int port) throws IOException


Creates a server socket, bound to the specified port.

public Socket accept() throws IOException


Listens for a connection to be made to this socket and accepts it. The method
blocks until a connection is made.

public Socket(InetAddress address, int port) throws IOException


Creates a socket and connects it to the specified port number at the specified IP
address.

public InputStream getInputStream() throws IOException


Returns an input stream for this socket.

public OutputStream getOutputStream() throws IOException


Returns an output stream for this socket.

For all stream classes

void close()throws IOException


Closes the stream.

Threads

public Thread(Runnable target)


Allocates a new Thread object.

public void start()


Causes this thread to begin execution.
ETSISI – UPM Departamento de Sistemas Informáticos
Sistemas Distribuidos Segundo parcial de prácticas. 60 m. 17 diciembre 2020

Apellidos, Nombre (mayúsculas): N. matricula:

Nota:

SE PIDE:
1. Cliente. Método remoteCopy
2. MonothreadFileServer. Clase FileService
3. Método main of MonothreadFileServer
4. Método main of MultithreadFileServer
5. Clase FileService MultithreadFileServer
Solución

1. Cliente. Método remoteCopy

public void remoteCopy(String fileName)


throws UnknownHostException, FileNotFoundException {

Socket clientSocket = null;


BufferedReader bufferedReader = null;
OutputStreamWriter outputStreamWriter = null;
BufferedWriter bufferedWriter = null;

try {
// Create a socket
clientSocket = new Socket(fileServiceHost, fileServicePort);

// Create a socket output char stream


outputStreamWriter = new OutputStreamWriter(clientSocket.getOutputStream());

// Create a socket buffered char stream


bufferedWriter = new BufferedWriter(outputStreamWriter);

// Write the name of the remote file into the socket output stream
bufferedWriter.write(fileName);
bufferedWriter.newLine();

// Open the file to transmit and read with buffering


bufferedReader = new BufferedReader(new FileReader(fileName));

// Write the lines of the file into the buffer.


// When the buffer is full write it on to the output stream until end of file
String line = null;
while ((line = bufferedReader.readLine())!= null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}

} catch (IOException e) {
System.out.println("Client: IOException: " + e.toString());
}

finally {
if (bufferedReader != null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}

if (bufferedWriter != null)
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}

if ( clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2. Servidor Monohilo. Clase FileService

public class FileService implements java.lang.Runnable {

Socket usrConnection = null;

public FileService(Socket usrConnection) {


this.usrConnection = usrConnection;
}

public void remoteCopy() {


// read the destination file name and file content from socket,
// and copy it to the destination file
InputStreamReader inputStreamReader = null;
BufferedReader bufferedReader = null;
OutputStreamWriter charOutputStream = null;
BufferedWriter bufferedWriter = null;

try {
// Get a buffered char inputStream from socket
inputStreamReader = new InputStreamReader(usrConnection.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);

// Read the name of the destination file


String destinationFile = bufferedReader.readLine();

// Creates the destination file, reading the name from the socket
charOutputStream = new FileWriter(destinationFile);
bufferedWriter = new BufferedWriter(charOutputStream);
String line = null;

// while not eof of socket line input stream, read line and write
// it to the file using buffering
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}

// Close the resources


bufferedWriter.close();
usrConnection.close();

} catch (IOException e) {
System.out.println("Remote Server: " + e.getMessage());
}
finally {
if (usrConnection != null)
try {
usrConnection.close();
} catch (IOException e) {
System.out.println("Remote Server: Unable to close the socket"+ e.getMessage());
}
}
}

public void run() {


System.out.println("Server New thread ");
this.remoteCopy();
}

}
3. MonothreadFileServer. Método Main

public class MonothreadFileServer {

public static void main(String[] args) throws IOException {


boolean shutdown = false;
ServerSocket serverSocket = null;
Socket usrConnection = null;
FileService fileService = null;

// Starting the service


System.out.println("Remote File Service Starting.");

serverSocket = new ServerSocket(9999);


System.out.println("Remote File Service Waiting for connection.");
while (!shutdown) {
usrConnection = serverSocket.accept();
fileService = new FileService(usrConnection);
fileService.remoteCopy();
}
serverSocket.close();
}
}

4. Servidor Multihilo

public class MultithreadFileServer {

public static void main(String[] args) throws IOException {


ServerSocket serverSocket = null;
Socket usrConnection = null;
boolean shutdown = false;

serverSocket = new ServerSocket(9999);


System.out.println("File Service Waiting for connection.");
while (!shutdown) {
usrConnection = serverSocket.accept();
System.out.println("File Service acepting new connection.");
Thread thread = new Thread(new FileService(usrConnection));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
serverSocket.close();
}
}

5. Servidor Multihilo. Clase FileService

public class FileService implements java.lang.Runnable {


Socket usrConnection = null;

public FileService(Socket usrConnection) {


this.usrConnection = usrConnection;
}

public void remoteCopy() {…}


public void run() {
this.remoteCopy();
}
}

También podría gustarte