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

Slides:



Advertisements
Presentaciones similares
Diseño de Bases de Datos
Advertisements

El mecanismo básico de interacción entre el usuario y un sitio web esta dado por el uso de formularios html. El server envía un formulario que el browser.
Verb Conjugations Easier than you think.
CC52N Computacion para el apoyo al trabajo grupal
Editing Slides With Polaris Office, you can create new .ppt and .pptx presentations or edit your presentation with ease.
El Socket Un socket es un extremo de un link de comunicación entre dos programas que corren en una red. El socket esta asociado (amarrado, bound) a ub.
The future tense ESSENTIAL ?: How can I describe events that will happen in the future?
Archivos y Búsqueda Secuencial
Los verbos regulares – ar What is an infinitive? An infinitive in both Spanish and English is the base form of the verb. In English, the infinitive.
Review, test strategies and packet answers.  1. Read through once for understanding, while HIGHLIGHTING key words (refer to handout from 9/18)  2. Go.
PROGRESSIVE IN PRESENT AND PAST
POP3 UCLV Mapas Conceptuales para la enseñanza de Redes de Computadoras.
PRONOMBRES DE COMPLEMENTO DIRECTO E INDIRECTO. ¿ Recuerdas? COMPLEMENTO DIRECTO Is a noun or a noun phrase that receives the action of the verb directly.
Qué haces en la escuela Interview, Conjugation Practice.
Resolución de Problemas y Algoritmos Uso de iteración con secuencias
Teoría de Sistemas Operativos
Implementacion de F.S. Asignación espacio Manejo espacio libre Emely Arráiz Ene-Mar 08.
Arquitectura NFS El servidor NFS exporta uno o más directorios
Arquitectura de Servidores
CPU 8088 vs. Pentium TEEL 4011 Prof. Jaime José Laracuente-Díaz.
Objective: I can recognize and accurately use gender agreement. Do Now: Match the following Spanish and English words: 1. Pelirroja a. Good-looking 2.
-AR Verbs In Spanish, there are three classes (or conjugations) of verbs: those that end in –AR, those that end in –ER, and those that end in –IR. This.
The Present Subjunctive The Subjunctive l Up to now you have been using verbs in the indicative mood, which is used to talk about facts or actual events.
DIRECT OBJECT PRONOUNS. DIRECT OBJECTS The object that directly receives the action of the verb is called the direct object. Mary kicked the ball. "Ball"
How to Conjugate Regular –AR – Er - IR Verbs in the Present Tense.
2: Capa Aplicación 1 Capa Aplicación: FTP ELO322: Redes de Computadores Agustín J. González Este material está basado en:  Material de apoyo al texto.
Bla bla from keyboard Talk client Talk Server Programemos algo bien simple Bla bla.
DHCP, DNS, WINS. Repaso..
Desarrollo de aplicaciones empresariales con Web Services
Universidad de Chile - Tupper 2007, Santiago - Fono/Fax: (56 2) cec.uchile.cl Módulo ECI - 11: Fundamentos de Redes de Computadores.
Programando servidores Postítulo Programando servidores Qué pasa en el servidor cuando el cliente trata de hacer un rendezvous ? El server empieza.
Servlets Servlets son módulos que extienden a servidores orientados a request/response, como por ejemplo Servidores Web “java-enabled”. Un servlet puede.
Diseño de Servidores Cc52n Que es un Servidor Básicamente se puede definir como un proceso que da un servicio El servicio en general se describe.
Arboles B (búsqueda externa)
First Grade – High Frequency Word Reading Competition Classroom Competition Created by: Malene Golding School Improvement Officer: Kimberly Fonteno.
Teoría de Sistemas Operativos Sistemas Archivos de Red
Digital Photography: Selfie Slides
Digital Photography: Selfie Slides Liliana Martinez 10/27/14 4b.
Second Grade – High Frequency Word Reading Competition Classroom Competition Created by: Malene Golding School Improvement Officer: Kimberly Fonteno.
First Grade – High Frequency Word Reading Competition Classroom Competition Created by: Malene Golding School Improvement Officer: Kimberly Fonteno.
Digital Photography: Selfie Slides Your Name Date Class Period.
Digital Photography: Selfie Slides By: Essence L. Thomas.
WWW. WIRELESS WIFI Wireless-Fidelity Es un mecanismo de conexión de dispositivos electrónicos de forma inalámbrica.
¿Qué haces en la escuela? Question words, objects, yo-go’s.
Digital Photography: Selfie Slides Your Name Date Class Period.
2: Capa Aplicación 1 Capa Aplicación: File Transfer Protocol ELO322: Redes de Computadores Agustín J. González Este material está basado en:  Material.
Digital Photography: Selfie Slides Your Name Date Class Period.
Introducción Nivel 4. Modelo OSI Propiedades Nivel 4 Entrega de mensajes garantizada. Entrega de mensajes en el mismo orden en el que fueron enviados.
TOPICS: SABER/CONOCER AND YO-GO VERBS Essential questions: How do I say whom and what I know? How do I use some other irregular verbs?
Digital Photography: Selfie Slides Anaiyah holiday 10/23/2014 6th.
Digital Photography: Selfie Slides
Digital Photography: Selfie Slides Caidyn Tanton 10/23/14 Period: 1.
Digital Photography: Selfie Slides Reid Steele 10/24/14 1st.
JUEVES, EL 10 DE SEPTIEMBRE LT: I WILL RECOGNIZE SOME NEW VOCABULARY WORDS. Go over tests & retake procedures Interpretive Assessment: numbers & alphabet.
ALC 59 Hoy es martes el 28 de febrero de Escribe 10 formas de transportación Thank you for having your ALC out and ready to get started.
Digital Photography: Selfie Slides Jaime lozano 28 oct 1.
Double Object Pronouns What happens when we have both direct and indirect object pronouns in the same sentence? What goes where? Information for this lesson.
ECOM-6030 PASOS PARA LA INSTALACIÓN DE EASYPHP Prof. Nelliud D. Torres © - Derechos Reservados.
To be, or not to be? Let’s start out with one of the most important verbs in Spanish: ser, which means “to be.”
Essential question: How do I say what I like and what interests/bores me?
LOS VERBOS REFLEXIVOS. WRITE: What is a reflexive verb? A reflexive verb describes when a person doing an action is also receiving the action.
Forming Questions ¡Aprenda! Forming Questions By Patricia Carl October 2013.
English Language II (2). English Language I (2) Warm-up.
Implementación de Sistemas de Archivos Estructura del Sistema de Archivos Implementación de Sistemas de Archivos Implementación de Directorios Métodos.
DLM Transact SQL Sesión I Introducción al SQL Server Uso de las herramientas de consultas del Transact SQL.
El Objeto Directo Direct Object Pronoun Sra. Altamirano.
Campanada guidelines in your composition notebook ¿Cómo es tu familia? (10 points) Ex. Hoy es Miercoles el 27 de enero First line will start with the date.
1 There are three basic ways to ask questions in Spanish. Can you guess what they are by looking at the photos and photo captions on this page?
LAS PREGUNTAS (Question Formation). Asking “yes/no” questions To ask spoken questions that can be answered with a simple “yes” or “no,” simply raise the.
To be, or not to be? Let’s start out with one of the most important verbs in Spanish: ser, which means “to be.”
Transcripción de la presentación:

Programming Servers

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)

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

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 ?)

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 DateClient2 DateServer

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

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

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; } TalkClient TalkServer

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

2)The sender tries a rendezvous with receiver 4) Send bytes 3) Read bytes from file5) Write bytes in file Repeat 3,4,5 until all the file is transmitted Uploading files 1)The reciver starts listening for Requests to send (upload) files ArchRecibidor.java ArchEnviador.java

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

1) Filename from keyboard 2) Request file 4) Send file 3) Read File5) Write file Repeat 3,4,5 until all the file is transmitted Requesting files by their names ArchServidor.java ArchCliente.java

1) Sends filename 4) Send file 2) Answers OK (or not OK) 3) Opens another socket A more robust version ArchClienteRobust.java ArchServidorRobust.java

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

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

Un ejemplo del servidor de Archivos (II) Situación guardardando información del estado: 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

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

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

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

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 ?

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

Arquitectura de un Servidor de Archivos Módulo Cliente Aplicación Servicio de Directorio Servicio plano de archivo (flat)

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

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

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

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

Ejemplo 1 el NFS Aplicación Sistema Virtual Sist Local Client NFS Sistema Virtual Server NFS Sist Local

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

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 (Tm cliente = Tm server ). Normalmente 3-30 seg para archivos y para directorios

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

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

The AFS Architecture Application Unix Kernel Local Sist Venus Vice Unix Kernel

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