33
Programming Servers

Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Embed Size (px)

Citation preview

Page 1: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Programming Servers

Page 2: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Programming the Server• What happens on the server when the client tries to establish a

rendezvous ?

• The server starts listening to requests on a ServerSocket

• After accepting the request the resulting connection is attached to another (normal) socket (same type as client’s socket)

Page 3: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Sockets at the Server Side (1)• The server should start by creating a server socket bound to a

certain port according to the protocol of the service.

ServerSocket listening;listening = new ServerSocket(5555);

• This will create the socket but the server is still not listening. To do this we should apply the following method to the socket:

Socket toClient = listening.accept();

• This sentence works the following way:–accept blocks the execution of the program until there is a petition for a rendezvous from a client (with calling = new Socket(host, 555)–When the requirement arrives, a tcp connection is established between the two computers. The client receives in its socket one end of this link and the server the other. The server side’s socket (from the Socket class) is chosen conveniently by the system

Page 4: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Sockets at the Server Side(2)• At the server side we can apply the same methods as we did at

the client side. Particularly we may need to open an input and an output data stream.

• After this, the server should implement the communication protocol which was established and published (by any other possible mean). It is important that both side follow this protocol in order not to block the communication and/or miss some data. This mean nothing else than following the “turn taking” rules of writing to and reading from the socket and the format of the data to be exchanged.

• Note that the server socket (and port) at which the server was originally listening to requests is not used anymore. This is a design issue (why ?)

Page 5: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

We will program now a date server for a computer which has no one

A Date Server

Date server 13 Client

1) Create the server socket 2) start listening

4) close the connection

3) answer with the date in another socket

DateClient2DateServer

Page 6: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

We will program now an echo server for a computer which has no one

An Echo Server

Date server 7 Client

1) Create the server socket 2) start listening

3) Request a line

4) answer with the same

Do 3 & 4 until client disconnects or sends a line with ** EchoServer EchoClient2

Page 7: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Bla bla from keyboard

Talk client Talk Server

Something rather simple to start

Bla bla

• The TalkServer waits for someone wishing to communicate• The TalkClient asks for a host name and tries the redezvous• After the communication is set up, everything the client user types in will be transmitted to the talk server and this will display it on the screenboard

Page 8: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Schema of both programms

Open server socket port =4444

While(true) {

accept call

open reading from socket

while (true) {

read line from socket

if (line.equals(“bye”))

break;

write line to screen

} //end of the call

}

s=new Socket(args[0],4444)

open writing to socket

while (true) {

read line from keyboard

write to socket

if (line.equals(“bye”))

break;

}

TalkClientTalkServer

Page 9: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Sockets: File transfer• We will now develop programs for

transmitting files• In the first case, the program receiving the

file starts listening for someone who wants to upload a file

• The sender knows where (hostname and port number) the server is listening and sends a rendezvous request

• The data transfer is done at the byte level in order to allow the transfer of non textual files

Page 10: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

2) The sender tries a rendezvous with receiver

4) Send bytes

3) Read bytes from file5) Write bytes in file

Repeat 3,4,5 untilall the file is transmitted

Uploading files1) The reciver starts listening for Requests to send (upload) files

ArchRecibidor.java ArchEnviador.java

Page 11: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Version 2 Requesting files

• The file server – Starts listening for requests on a “known” port– When a request is accepted, a string corresponding to

a filename is read– Opens locally a file with this name, reads it and

sends it to the client (byte-wise)

• The file client– Tries a rendezvous with the server– Reads a filename from keyboard and send it to the

server– Reads bytes from socket and write them to a file

Page 12: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

1) Filename from keyboard

2) Request file

4) Send file

3) Read File5) Write file

Repeat 3,4,5 untilall the file is transmitted

Requesting files by their names

ArchServidor.java

ArchCliente.java

Page 13: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

1) Sends filename

4) Send file

2) Answers OK (or not OK)

3) Opens another socket

A more robust version

ArchClienteRobust.java ArchServidorRobust.java

Page 14: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Servidores Con o sin Estado• ¿ Qué es el Estado ?

– El “estado” es la información que los servidores mantienen acerca de la interacción que se lleva a cabo con los clientes.

• ¿ Para qué ?– Generalmente se hace más eficiente el comporatamiento de los

servidores con información. Información muy breve mantenida en el servidor puede hacer más chicos los mensajes o permite producir respuestas más rápido.

• ¿ Y entonces por qué se evita a veces ?– Es fuente de errores: mensajes del cliente pueden perderse,

duplicarse llegar en desorden. El cliente puede caerse y rebootear, con lo cual la información que tiene el servidor de él es errónea y también sus respuestas

Page 15: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Un ejemplo del servidor de Archivos

El servidor espera que un cliente se conecte por la red. El cleinte puede mandar 2 tipos de requerimientos: leer o escribir datos en un archivo. El servidor realiza la operación y retorna el resultado al cliente.

• Situación sin guardar información acerca del estado: – Para leer, el cliente debe siempre especificar: nombre de archivo,

posición en el archivo desde dónde debe extraer los datos y el número de bytes a leer.

– Para escribir debe especificar el nombre completo del archivo, el lugar donde quiere escribir y los datos que quiere escribir

Page 16: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Un ejemplo del servidor de Archivos (II)

• Situación guardardando información del estado: Handle Filename Posición

1 miArchivo.txt 02 unDocumento.doc 4563 unJuego.exe 384 Hola.java 128

• Cuando el cliente abre un archivo se crea un entrada en la tabla. A la entrada se le asigna un handle para identificar el archivo y se le asigna la posición actual (inicialmente 0). El cliente recibe el handler como respuesta.

• Cuando el cliente quiere extrer datos adicionales le envia el handle y la cantidad de bytes. Esto es usado por el servidor para saber gracias a la tabla de dónde exactamente debe extraer los datos (debe actualizar la posición para que para la próxima vez se pueda hacer lo mismo).

• Cuando el cliente termina la lectura/escritura envía un mensaje para sea eliminada la entrada de la tabla

Page 17: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Otro ejemplo consulta bases de datos

El cliente hace consultas a bases de datos. En la primera consulta el resultado es muy grande. Quiere refinar la consulta basada e los resultados obtenidos hasta ahora

• Situación sin guardar información acerca del estado: – El servidor debe mandar todo el resultado de la consulta al

cliente, el cliente debe mantenerla

– El cliente debería ser capaz de hacer consultas localmente o si no mandar la query con el conjunto de resultados obtenidos la vez anterior

Page 18: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Otro ejemplo carro de compras

El servidor espera que un cliente se conecte por la red. Consulte los productos que hay y vaya seleccionando productos. El cliente se mueve entre la búsqueda y la selección

• Situación sin guardar información acerca del estado: – La lista completa de items seleccionada por el cliente debe ser

constantemente transmitida entre cliente y servidor

Page 19: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Otro ejemplo transacciones bancarias

El servidor necesita que el cliente se identifique con username y password para hacer una transacción o consulta

• Situación sin guardar información acerca del estado: – Por cada transacción que quiere hacer el cliente se va a necesitar

la información de autentificación del cliente

Page 20: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Problemas al mantener un estado

• En el servidor de Archivo ?• En las consultas a una base de datos ?• En un carro de compras ?• En transacciones ?

Page 21: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

1 An attempt of writing a file server with state

• This implementation will server sequential text file (can be easily changed)

• It receives requests for opening a file for reading or writing, read next line, write line.

• The “state” is stored in a hashtable which contains objects of the classes BufferedReader and PrintWriter

• See

2 An example of a file server without state

• This implementation will server random access files (can be easily changed)

• It receives requests for reading/writing a certain number of bytes from/into a file

• See fileservernostate.java

FileServerWitState.java

FileServerNoState.java

Page 22: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Arquitectura de un Servidor de Archivos

MóduloCliente

Aplicación Servicio de Directorio

Servicio plano de archivo (flat)

Page 23: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Componentes• Flat File Service: Implementa las operaciones

directamente sobre los archivos. Trabaja con Unique File Identifieres (UFID). Se genera uno nuevo por cada archivo

• Directory Services: Cliente de el FFS, provee un mapeo entre los UFID y los nombre textuales de los archivos y las funciones necesarias para administrar directorios y obtener las UFID. Los directorios se guardan como archivos planos.

• Módulo Cliente: Corre en cada computador, integra y extiende las operaciones del FFS y DS en una aplicación interfaz usada por los programadores. Posee información acerca de la localización de archivos en la red. Provee eficiencia a través de un cache

Page 24: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Modelo de Interfaz para FFS• read(FileId, i, n) :le hasta n bytes de un archivo a partir de la

posición i los que retorna en un arreglo

• write(FileId, i, Datos): escribe la secuencia de datos en el archivo a partir de la posición i extendiéndolo en caso

• create() : crea un archivo nuevo de largo 0 y devuelve el UFID para él

• delete(FileId) : borra el archivo

• getAttributes(FileId) : retorna una estructura con los atributos

• setAttributes(FileId, attr) : pone los atributos según la estructura

Page 25: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Controles de acceso• En un sistema local el chequeo se hace sólo al abrir el archivo

y los derechos se conservan • en un sistema distribuido los chequeos se deben hacer a nivel

de servidor. Para que el servidor siga siendo stateless se pueden usar 2 estrategias:– El chequeo se hace cuando el nombre es convertido en UFID y el

resultado es codificado en forma de capacidad que se retorna al cliente, el cual lo usa para futuros accesos

– La identificación del usuario se hace cada vez que se manda un request y el chequeo se hace para cada operación

• El segundo es más usado (en NFS y AFS) por su simplicidad, pero ninguno garantiza seguridad en el caso de identidad suplantada

Page 26: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Modelo de interfaz para Directory Service

• Lookup(Dir, File) localiza el nombre de texto en el directorio y retorna el UFID

• AddName(Dir, Name, File) Si Name no estaba en el directorio dado añade el par (Name,File) en el directorio modificando el archivo pertinente

• UnName(Dir, Name) el par (Name, file) correspondiente es borrado del directorio

• getNames(Dir) retirna la lista de nombres que contiene un directorio

Page 27: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Ejemplo 1 el NFS

Aplicación

Sistema Virtual

SistLocal

ClientNFS

Sistema Virtual

ServerNFS

SistLocal

Page 28: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Características de NFS• La comunicación es por medio de RPC y es abierta en el

servidor, que reside en el kernel• La identificación de archivos es por medio de los llamados

file handters consistentes en:• Filesystem identifier• i-node number or file• i-node gerneration number

• El “estado” se guarda en el cliente en un v-node• Autentificación del cliente en cada llamada mandando user ID y group

ID• Los servicios de flat file y directory están integrados• El servicio de mount provee un link a un sistema remoto

Page 29: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Cache en NFS• Cache en Unix: buffer cache, read ahead, delayed write

• Cache en servidor: datos de escritura se guardan en memoria cache y son escritas antes del reply al cleinte. En la versión 3 se guarda todo en cache hasta que se recibe la operación commit para ese archivo (buffer lleno o close)

• Cache en el cliente: resultados de read, write, getattr, lookup y readdir se almacenan localmente, lo cual puede introducir inconsistencias en versiones en los distintos clientes ya que escrituras de un cliente no se actualizan en seguida en los otros. Los clientes son entonces responsables de mantener actualizados sus caches por medio de timestamps: Tc= tiempo de la última actualización, Tm= tiempo de modificación. A un tiempo T el cache será válido si (T - Tc < t) o (Tmcliente = Tmserver). Normalmente 3-30 seg para archivos y 30-60 para directorios

Page 30: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Interfaz de NFS simplificada• read(FileId, i, n) :le hasta n bytes de un archivo a partir de la

posición i los que retorna en un arreglo

• write(FileId, i, Datos): escribe la secuencia de datos en el archivo a partir de la posición i extendiéndolo en caso

• create() : crea un archivo nuevo de largo 0 y devuelve el UFID para él

• delete(FileId) : borra el archivo

• getAttributes(FileId) : retorna una estructura con los atributos

• setAttributes(FileId, attr) : pone los atributos según la estructura

Page 31: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Ejemplo 2: El AFS• Apunta a lograr mejor performance en situaciones de

escalabilidad– Whole-file serving: El contenido de todo los directorios archivos son

traspasados al cleinte

– Whole-file caching: Los archivos transmitidos son guardados en cache local. Normalmente varios cientos de archivos ! El cache es casi permanente.

– Cuando se hace un open del archivo se transmite el archivo entero si no estaba

– las operaciones de escritura/lectura se hacen localmente

– Con el close, se transmite una copia modificada al servidor

– Debe

Page 32: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

The AFS Architecture

Application

Unix Kernel

LocalSist

Venus

Vice

Unix Kernel

Page 33: Programming Servers. Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to

Consistencia del Cache• Cada vez que se traspasa un archivo del servidor a un cliente se provee

de una promesa de callback, que garantiza que cuando otro cliente modifique el archivo este será notificado

• El callback puede estar en dos estados: valido o cancelado• Cuando el archivo es traspasado al cliente el callback se pone en

válido. Cuando se recibe un callback del servidor (porque el archivo fue modificado) se pone en cancelado

• Cada vez que el cliente abre un archivo busca si está en su cache. Si está se revisa el callback. Si está cancelado se trae una copia nueva del archivo, si está válido, se usa el archivo del cache

• Si la estación de trabajo se reinicia (por que se apagó o se cayó) pide para cada archivo de su cache el timestamp de la última modificación

• si la última modificación es consistente con la copia se pone el callback en válido, si no en cancelado