Post on 02-Apr-2015
Protocolos TCP y UDP (I)
• Importancia para el programador: – Al elegir un protocolo con el cual conectarse con otra máquina
determina el nivel de confiabilidad de la transmisión de datos, lo cual repercute en la forma de programar las aplicaciones.
• TCP provee alta confiabilidad: los datos mandados serán recibidos si una conexión entre los 2 computadores se pudo establecer. Hay un protocolo subyacente que se preocupa de retransmitir, ordenar....
• Con UDP el programador debe proveer el protocolo para el caso que se pierdan datos o lleguen en otro orden.
– La forma de programar el envío recibo de datos con ditintos protocolos es también distinta:
• En TCP la forma de transmitir datos es normalmente como un flujo de datos por la conexión establecida.
• Con UDP se deben armar paquetes de datos que son pasados a la internet para ser transmitidos “con el mejor esfuerzo”.
Protocolos TCP y UDP (II)• ¿ Cuándo usar uno u otro ?
– TCP impone una carga bastante mayor a la red que UDP, por lo cual se debe evitar si es “razonablemente posible”
• ¿ Cuándo es “razonablemente posible” ?– Podemos esperar pérdidas cuando los datos tienen que viajar a traves de varias
redes por la internet.– Dentro de una LAN las comunicaciones UDP son relativamente confiables– Algunas veces la información que no llegó a tiempo no tiene sentido
retransmitirla porque ya está obsoleta (¿cuándo?).
• En general se recomienda, especialmente a principiantes, usar sólo TCP en sus aplicaciones. El estilo de programación es más secillo. Los programadores sólo usan UDP si el protocolo de la aplicación misma maneja la confiabilidad, si la aplicación requere usar broadcast o multicast de hardware o la aplicación no puede tolerar el overhead de un circuito virtual.
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: 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
Stateless vs. Stateful servers: the problem of reading a remote file by steps. File reading requests arrive with dealy
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request open file XYZ
Answer file XYZ exists and ready
A stateless server means it does not remember previous requests
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request read bytes 0 to 49 from file XYZ
Answer the content of the bytes
The client must provide all the information again !
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request read bytes 50 to 99 from file XYZ
Answer the content of the bytes
This may cause a lot of network traffic, especially if there are many
clients
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request read bytes X to X+50 from file XYZ
Answer the content of the bytes
Stateful Server: it maintains some information abut what clients did
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request open file XYZ
Answer: file pointer to file XYZ
Pointer File Position
0 XYZ 0
1 FILE ZXY 50
The information the client has to pass to the server is much smaller
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request 0, read 50
Answer: the content
Pointer File Position
0 XYZ 50
1 FILE ZXY 50
The information at the server should be updated with every request
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request 0, read 50
Answer: the content
Pointer File Position
0 XYZ 100
1 FILE ZXY 50
It is important to close the file !!!
A SERVERA CLIENT
Open file XYZread first 50 byteswhile (not end of file XYZ)
read next 50 bytesclose file
?
Request 0, read 50
Answer: the content
Pointer File Position
0 XYZ 100
1 FILE ZXY 50
Un ejemplo del servidor de Archivos
• Posibilidades de errores • La red manda dos veces el datagrama con requerimiento de lectura
• Si el computador del cleinte se cae y rebootea el programa.
• Si el computador se cae antes de poder “des-registrarse”
• Si otro cliente se conecta en el mismo port que el que se cayó sin avisar
En una internet real, donde las máquinas pueden caerse y rebootear y los mensajespueden perderse, llegar atrasados, duplicados o en orden incorrecto un servidor con manteción de estado puede resultar difícil de programar para hacerlo tolerante a los errores.
Arquitecturas para Aplicaciones Distribuidas
• Servidores como Clientes– Los programas no siempre se comportan definitivamente como
servidores puros o como clientes puros. Ej: un servidor de archivos que necesita un timestamp para registrar el último cambio.
– Cuando todas las aplicaciones deben comportarse simultáneamente como servidores y clientes: ¿ cómo organizar las comunicaciones ?
• Cada aplicación abre un canal con otra aplicación (configuración red)
• Hay un servidor de comunicaciones y todoas las aplicaciones se comunican con él (configuración estrella).
Arquitecturas para Aplicaciones Distribuidas
• Cada par de aplicaciones que necesitan comunicarse abren un canal exclusivo
• Se abren a lo más n*(n-1)/2 canales para n aplicaciones
• Ventajas: – un canal exclusivo, no hay cuellos de botella
• Desventajas: – todas las aplicaciones deben saber cómo comunicarse con las demás. – La dinámica se vuelve más complicada (entrada/salida de aplicaciones)
Arquitecturas para Aplicaciones Distribuidas
• Las aplicaciones envían sus requerimientos de comunicación a un servidor y éste se encarga de mandarlas a su punto de destino final.
• Se abren a lo más n*(n-1)/2 canales para n aplicaciones
• Ventajas: – Es más fácil manejar los parámetros de la comunicación
• Desventajas: – se puede saturar el servidor o las líneas.
The channel which server and client use to communicate (either int TCP or
UDP) is called SOCKET
A SERVER 1
When a server wants to start listening it must create a socketbound to a port. The port is specified with a number.
A SERVER 2
A SERVER 3
www.thisserver.jp
4444
3333
5555
If a client wants to communicate with server 1 should try to communicate with computer www.thisserver.jp through port 4444
Internet : two different ways to deliver a message to another application
The UDP: User Defined Package: like writing a letter
TCP or UDP
Applications’ programmers decide on this according to their needs
UDP: communication with datagramsDATAGRAM: an independent, self-contained message sent over the internet whose arrival, arrival time and content are not guaranteed (like regular mail in some countries....)
A SERVER A CLIENT
4444
www.waseda1.jp
www.waseda1.jp
message
4444
Once a server is listening, the client should create a datagramwith the server’s address, port number and, the message
www.waseda2.jp
?
Sending datagrams with UDP protocol
Then it should open a socket and send the datagramto the internet. The “routing algorithm” will find the way to the target computer
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
?
Before the datagram leaves the client, it receives the address of the originating computer and the socket number
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
!
Sending datagrams with UDP protocol
Sending datagrams with UDP protocol
After the datagram is sent, the client computer may start hearing at the port created for sending the datagram if an answer from the server is expected
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
?
Sending datagrams with UDP protocol
The server can extract the client’s address and port number to create another datagram with the answer
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
answer
?
Sending datagrams with UDP protocol
Finally is sends the datagram with the answer to the “client”. When a datagram is sent there is no guarantee that it will arrive to the destination. If you want reliable communication you should provide a checking mechanism, or use ...
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
?
TCP: communication with data flow
With TCP a communication channel between both computers is built and a reliable communication is established between both computers. This allows to send a data flow rather tan datagrams.
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
?
TCP: communication with data flow
After the client contacts the server, a reliable channel is established. After this, client and server may begin sending data through this channel. The other should be reading this data: They need a protocol !!!!
A SERVER A CLIENT
4444
www.waseda1.jp
3333
www.waseda2.jp
bla bla bla bla
TCP: How is reliability achieved ?The internet itself works only with the datagram paradigm. Internet frames are may “get lost” (destroyed): For every frame delivered carrying a part of the data flow there is a confirmation!
Sending bla bla bla Sending 1st bla
Ack 1st bla
Sending 2nd bla
Ack 2nd bla
Sending 3rd bla
Ack 3rd bla
What if a message get lost ?The server waits a certain amount of time. If it does not receive any confirmation it sends the message again.
Sending bla bla bla
Sending 1st bla
Ack 1st bla
Sending 2nd bla
Sending 2nd bla again
Ack 2nd bla
No confirmation !!!
LOST !!!
The Window for improving efficiencyThe transmitter will handle a set of not acknowledged packets
Sending 1st bla
Ack 1st bla
Sending 2nd bla
Ack 2nd bla
Sending 3rd bla
Ack 3rd bla
When do programmers should use UDP or TCP ?
- TCP generates 6 times more traffic than UDP- It is also slower to send and receive the messages
- Reliable- Complete
- Valid in a certainperiod of time
- No need of speed
UDP TCP
- not complete- fast- valid in a very short period of time
Mark with a + the applications that need TCP and with a = the applications that
can use UDP
E-Mail Video conference
Temperature every second
Web server and client
Stock values every 5 seconds
The Multicast paradigm
PROG1
PROG2
PROG2
PROG2
Attending more than a client: The sequential server
A SERVERA CLIENT
A CLIENT
A CLIENT
4444
During the conversation the server is not listening at the port 444
A SERVERA CLIENT
A CLIENT
A CLIENT
4444
Only after the server is ready with the first client it can listen to the
port 444 again
A SERVERA CLIENT
A CLIENT
A CLIENT
4444
The service may be to transfer a file. The user at the client should first
send the filename
A SERVERA CLIENT
A CLIENT
A CLIENT
4444
What if the server has to wait too much for a client to type in a file
name ?
A SERVERA CLIENT
A CLIENT
A CLIENT
4444
Timeout
Concurrent Servers: there are separate processes to attend the port
and to transfer the file
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
After the client contacts the server, the server creates another process to attend the client and keeps listening to the port
4444 for another
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
While the new process is serving the first client, the second client can contact the
server at the port 4444
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
And the server creates another process
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
Now the third client contacts the server
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
And a third slave process or thread is created
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
Every layer has the illusion to be talking to the correspondent one in the other
application
A SERVER
A CLIENT
A CLIENT
A CLIENT
4444
The UDP: User Defined Package: like writing a letterRead write sequence
UDP or TCP communication
Internet frames and addresses
electricpulses
There are now a lot of resources between the application and transport layer
which make distributed programming much easier
Libraries for distributedprogramming (middleware)
RPC, CORBA, RMI
For example, the RMI mechanism in JAVA (similar to CORBA)
Creates and publishesa Remote Object
Other applications use and share this object (data)
2- InterNetworking con Java• ¿ Por qué JAVA ?
– En este curso: Los programas son más simples => se peude usar más tiempo en explicar la lógica de los programas que para explicar las instrucciones del lenguaje.
– En general: Java nace cuando la internet ya está madura (1993-4) => nace “sabiendo” que existe TCP/IP y que la programación distribuida es importante, lo que se nota en el diseño.
– Además de las típicas funcionalidades básicas de comunicación (comunicación por canales TCP y UDP) incorpora otras de alto nivel de abstracción: RMI, Applets, JDBL, URL
• ¿ Siempre es mejor JAVA ?– No, Java es multiplataforma por lo tanto sólo puede hacer cosas que sean
comúnes a todas las plataformas.
– Con la estandarización de TCP/IP como red virtual para todos los equipos esto es cada vez menos importante. Aún así hay cosas: Nombres y ports sólo se pueden asociar en C ya que es exclusivo de UNIX.