You are on page 1of 82

Fonaments de Xarxes

EE - UAB

Tema I.3 Capa d'Aplicació:


Aplicacions i serveis distribuïts
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 Objectius d’aprenentatge
 Conèixer breument el model client/servidor.
 Conèixer breument diferents models de
comunicació distribuïda.
 Conèixer les bases de la programació
d’aplicacions distribuïdes mitjançant sockets,
com a base de la primera pràctica de l’assignatura.

R. Martí - 2023/24 2
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 3
Capes de TCP/IP
 [Usuari] (sense comunicació i fora el model de capes
TCP/IP)
 [Interfície i comandes d’usuari i codi sense comunicacions]
5./7. Aplicació
 Comunicació específica de cada aplicació (programa)
 Codificació de caràcters, encriptació, etc.
 [Establiment i control de sessions (diàleg [dins connexions])
entre aplicacions finals]
4. Transport
 Comunicació (fiable, amb connexió) extrem a extrem (i segmentació, si
cal)
3. Xarxa / Internet
 Comunicació entre xarxes
2. Enllaç de dades / Accés a Xarxa
 Comunicació (fiable) equip-xarxa, i entre equips (incloent el router)
dins una mateixa xarxa de trames (“paquets”)
1. Física / Medi físic
 Transmissió de bits dins el medi físic

R. Martí - 2023/24 4
TCP/IP: serveis i capes
7. Aplicació
 HTTP, SMTP, POP3, IMAPv4, DNS, FTP, etc.
4. Transport
 TCP (fiable, connexió), UDP (no fiable, no connexió), RTP (7?), SCTP
3. Xarxa / Internet
 Per a TCP/IP, aquí va l’Internet Protocol (IP)
 També es poden considerar part de la capa de xarxa protocols
 obligatoris com ICMP i IGMP, que van sobre IP
 d’encaminament com OSPF, que van sobre IP
 d’encaminament com BGP I RIP, que per diverses raons van sobre TCP i UDP
respectivament
2. Enllaç de dades / Accés de xarxa
 LLC, MAC [“Ethernet”, “Wi-Fi”, Token ring, ...], ATM, PPP, etc.
 ARP va sobre la capa d’enllaç, però es pot considerar dins aquesta capa.
1. Física / Medi físic
 Medi físic, i tècniques de codificació, T1, E1, ADLS, etc.
 Els protocols d’Enllaç a vegades inclouen especificacions de capa física
(Ethernet, “Wi-Fi”, ...)

R. Martí - 2023/24 5
 Local application Usuari

Interfície
d'Aplicació

Client
Interfície
"Aplicació"
[de Servei]

Servidor

 Distributed application
usuari

Usuari

Interfície
client servidor
d'Aplicació

Client
Client Interfície
[de Servei]
Protocol d’Aplicació
C. Aplicació C. Aplicació
Interfície Protocol Protocol de Transport
[de Servei]
C. Transport C. Transport

Servidor Capa de Xarxa Connexió de Xarxa


i inferiors

R. Martí - 2023/24 6
The base paradigm
 The base paradigm
 The client / server paradigm is the primary model
for interaction between cooperative applications.

 -> This interaction is the basis for most


network communications, and it is
fundamental because it helps understanding the
basic concepts of distributed applications.

R. Martí - 2023/24 7
Client and Server
 Server
 Any program providing a service, simple or complex, which is
accessible from a network.
 Passive side.
 Accepts a request, executes the service, and returns a result.
 Client
 Program sending a request to a server and waiting for a response.
 Active side.
 Different servers can provide the same service in several hosts
or even the same host.
 The interaction between client and server is often called
request/response behavior.
 Client and servers can be in different programming language
 But both must support same communication protocol

R. Martí - 2023/24 8
Client and Server
 Normally:
 A server starts its execution and accepts
requests and sends responses for ever.
 The client, as a general rule, finishes its
execution after having done a finite number of
service requests.

 The server listens for requests on a well-known


port that has been previously reserved (binded)
to the service it provides.
 The client uses an unused unreserved
ephemeral port.

R. Martí - 2023/24 9
Client/server levels
 3 levels in the client/server paradigm:
 Interface level [Presentation]
 Allows the interaction of the user, or another application,
with the (rest of the) application.
 Processing level [Application]
 Central core of the application processing data.
 Data level [Data access + Data storage]
 Maintenance of the data needed by the applications.
 Normally:
 clients have only the interface level,
 servers have the other two (processing + data).

R. Martí - 2023/24 10
 This division is not always like this.
 We can have clients and servers with other levels,
 We can have levels divided between clients & servers.
 Only need to know the client<->server Service interface

R. Martí - 2023/24 11
Modern architectures
 There are more modern architectures:
 Three-tiered
 The server is client at the same time to other server(s).
• Client <-> Server+Client 2 <-> Server 2
• E.g. Interface <-> Processing <-> Data
 Horizontal distribution
 Several servers distributed along different locations
(load balancing).
• Client <-> [Server 1 | Server 2 | ... | Server n]
 Peer-to-peer distribution
 Clients collaborate with each other.
 Symmetry between all users: all are “clients” and
“servers” simultaneously.
• Client+Server <-> Client+Server

R. Martí - 2023/24 12
Middleware
 Sometimes, difficult to integrate multiple clients and servers
from multiple vendors -> different standards
 One solution: Middleware:
 Software between or in the middle of any of the 3 application levels
 In C/S: On client, on server, or split between client and server
 “Connects” layers with complementary functionality & different
interfaces
 E.g. between Processing level

R. Martí - 2023/24 13
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC (Remote Procedure Calls)
 RMI (Remote Method Invocation)
 Paquets/Datagrames
 Fluxos (Streams)
 Missatges (Message Oriented Communication, MOM)
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 14
Communication models
 Communication is a basic part of distributed
applications.
 It is always based on a message interchange
system at a low level.
 We will see the following models (/mechanisms):
 Remote Procedure Calls (RPC)
 Remote Method Invocation (RMI)
 Packets/Datagrams
 Streams
 Message oriented communication (MOM)
 Web services
 New paradigms

R. Martí - 2023/24 15
Models de comunicació distribuïda
 RPC (Remote Procedure Calls) usuari

 Operacions remotes (p. ex. Oper. “c”) client servidor

 RMI (Remote Method Invocation)


Interfície
[de Servei]
Protocol d’Aplicació
C. Aplicació C. Aplicació

 Objectes remots (amb paràmetres i Mecan. Com.


Protocol del Mecan. de Com.
Mecan. Com.

funcions) (p. ex. Java) Capa de Transport Connexió de Transport

 Paquets/Datagrames *
i inferiors

 Enviament de paquets/datagrames (p. ex. UDP *)


 Fluxos (Streams) *
 Enviament [“continu”] de flux de bytes, síncron o asíncron
(p. ex. TCP *)
 Missatges (Message Oriented Communication, MOM)
 Intercanvi de missatges a través de bústies no síncrones

R. Martí - 2023/24 16
Models de comunicació distribuïda
 Serveis web (Web services)  Serveis Web - SOAP request:
 Mòduls software discrets POST /InStock HTTP/1.1
cadascun amb 1 operació Host: www.example.org
(servei) específica Content-Type: application/soap+xml;
charset=utf-8
 Operacions remotes codificades Content-Length: nnn
en XML a través de
HTTP+HTML (web) <?xml version="1.0"?>
<soap:Envelope
 Nous paradigmes xmlns:soap="http://www.w3.org/2001/1
2/soap-envelope"
 Codi Mòbil soap:encodingStyle="http://www.w3.or
 El codi es mou d'un host a un g/2001/12/soap-encoding">
altre, executant-se en arribar
a la màquina remota. <soap:Body
xmlns:m="http://www.example.org/s
 Agents Mòbils Software tock">
(Software Mobile Agents) <m:GetStockPrice>
<m:StockName>IBM</m:StockName>
 El codi i dades estan en un
</m:GetStockPrice>
agent de programari.
</soap:Body>
 L'agent és “intel·ligent” i
autònom i pot prendre </soap:Envelope>
decisions de comunicació,
mobilitat, etc.

R. Martí - 2023/24 17
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 18
Capes de TCP/IP
 [Usuari] (sense comunicació i fora el model de capes TCP/IP)
 [Interfície i comandes d’usuari i codi sense comunicacions]
5./7. Aplicació
 Comunicació específica de cada aplicació (programa)
 Codificació de caràcters, encriptació, etc.
 [Establiment i control de sessions (diàleg [dins connexions]) entre
aplicacions finals]
4. Transport
 Comunicació (fiable, amb connexió) extrem a extrem (i
segmentació, si cal)
3. Xarxa / Internet
 Comunicació entre xarxes
2. Enllaç de dades / Accés a Xarxa
 Comunicació (fiable) equip-xarxa, i entre equips (incloent el router)
dins una mateixa xarxa, de trames (“paquets”)
1. Física / Medi físic
 Transmissió de bits dins el medi físic

R. Martí - 2023/24 19
TCP/IP: serveis i capes
7. Aplicació
 HTTP, SMTP, POP3, IMAPv4, DNS, FTP, etc.
4. Transport
 TCP (fiable, connexió), UDP (no fiable, no connexió), RTP (?), SCTP
3. Xarxa / Internet
 Per a TCP/IP, aquí va l’Internet Protocol (IP)
 També es poden considerar part de la capa de xarxa protocols
 obligatoris com ICMP i IGMP, que van sobre IP
 d’encaminament com OSPF, que van sobre IP
 d’encaminament com BGP I RIP, que per diverses raons van sobre TCP i UDP
respectivament
2. Enllaç de dades / Accés de xarxa
 LLC, MAC [“Ethernet”, “Wi-Fi”, Token ring, ...], ATM, PPP, etc.
 ARP va sobre la capa d’enllaç, però es pot considerar dins aquesta capa.
1. Física / Medi físic
 Medi físic, i tècniques de codificació, T1, E1, ADLS, etc.
 Els protocols d’Enllaç a vegades inclouen especificacions de capa física
(Ethernet, “Wi-fi”, ...)

R. Martí - 2023/24 20
Sockets
 Operating System software libraries to send and
receive TCP|UDP/IP messages
 Connection-oriented or connectionless
 Provide communication through the "known"
communication protocols
 TCP (stream), UDP (datagram), IP, etc.
 The set of primitives for using this interface does
not belong to the TCP/IP standards.
 Original development as a part of the Unix OS

 Based on simple devices and files calls:


 connect, send, recv, write, read, close, …

R. Martí - 2023/24 21
Sockets
 Teoria:

 Sovint:

R. Martí - 2023/24 22
TCP / UDP
 4. Transport
 Comunicació extrem a extrem
 TCP:
 Fiable
• Totes les dades arriben al destí final; si no arriben, el protocol les
recupera/reenvia transparentment. => retard
 Amb connexió
• Intercanvi de paquets inicial per connectar-se els 2 extrems
• Totes les dades es lliuren a la capa d’aplicació en l’ordre que han estat
enviades (si arriben desordenades, abans s’ordenen) => retard
 Amb segmentació
• Les dades es parteixen en segments en funció de la mida permesa per
la xarxa
 UDP:
 No fiable
• Les dades es poden perdre i no lliurar-se a l’aplicació
• Les dades es lliuren a la capa d’aplicació en l’ordre d’arribada (pot ser
desordenades respecte l’enviament) => no retard

R. Martí - 2023/24 23
 When a socket is created, a file descriptor is
assigned to it for future access and use.
 The numbering space for the assignment of descriptors is
shared with the file and device systems.
 The sockets are more complex than files though:
 there are more parameters and options to be specified.

 Main basic primitives (system calls):


 socket() bind() listen() accept()
 connect() shutdown() close() select()
 send() recv() write() read()
 sendto() recvfrom()

R. Martí - 2023/24 24
 By default, sockets are in "blocking" mode:
 When you call recv() / read(), control isn't
returned to your program until at least one byte
of data is read from the remote site.
 Also for send() / write(), connect(), etc.:
connection "blocked" until operation is complete.
 This process of waiting for data to appear is
referred to as "blocking".

R. Martí - 2023/24 25
result = socket(pf, type, prot)
Creates a socket. (client & server)(TCP & UDP)
bind(socket, localaddr, addrlen)
Binds a socket to a port. (s [& c])(T & U)
listen(socket, qlength)
Prepares a socket for receiving connection (passively opens connections). (s)(T)
Marks a socket as passive & defines the max. length of pending connections queue.
newsock = accept(socket, addr, addrlen)
Listens for & accepts a new connection. (s)(T)
connect(socket, destaddr, addrle)
Establishes a connection. (c)(T)
shutdown(socket, mode)
Partially closes the bidirectional connection. (c & s)(T)
close(socket)
Decreases the reference counter associated with the socket. (c & s)(T & U)
If the counter reaches zero, the socket is destroyed (and closed).
select(ndesc, indesc, outdesc, excdesc, timeout)
Indicates whether if a socket is ready for sending, if data is already available from a
socket to be read, or if a timeout with no activity in the socket has expired. (c & s)(T & U)

R. Martí - 2023/24 26
send(sock, message, length, flags)
Sends data through a connected socket. (c & s)(T)
recv(sock, buffer, length, flags)
Receives data from a connected socket. (c & s)(T)
write(socket, buffer, length)
Writes data to a connected socket. (c & s)(T)
read(socket, buffer, length)
Reads data from a connected socket. (c & s)(T)

sendto(sock, message, length, flags, destaddr,


addrlen)
Sends data through a connectionless socket. (c & s)(U)
recvfrom(sock, buffer, length, flags, fromaddr,
addrlen)
Receives data from a connectionless socket. (c & s)(U)

R. Martí - 2023/24 27
 Main C library functions related with sockets:
 gethostbyname* getpeername
 getsockname getsockopt
 setsockopt gethostbyaddr
 getprotobyname getprotobynumber
 getservbyname getservbyport

 These are library functions and not system


calls.
 System calls: functions provided by the kernel
 Library calls: functions within C/program libraries

R. Martí - 2023/24 28
gethostbyname(namestr)*
To get information of a host (name, address, …) from its
domain name or IPv4 address (dotted quad string).
getpeername(socket, destaddr, addrlen)
To know the address of the destination socket to which we are
connected.

* gethostbyname() and gethostbyaddr() are obsolete.


Applications should use getaddrinfo() and getnameinfo()
instead.

R. Martí - 2023/24 29
Little-endian vs Big-endian
 2 possibles maneres d’ordrenar en memòria les dades de més
d’1 octet en 1 equip/host (“format host”):
 Little-endian: 1r els octets menys significatius
 Big-endian: 1r els octets més significatius
 Això aplica a:
 short: 16 bits (port)
 long: 32 bits (adreça IP)
 …
 Però a sockets cal desar-les i usar-les de manera “estàndard”, en
“format xarxa” (big endian), independent de l’equip.
 struct hostent
 .h_addr
 struct sockaddr_in
 .sin_port i .sin_addr
 Calen funcions que converteixin del format intern del host al
format de la “xarxa” (format “sockets”).
 En cada sistema concret, inverteixen o no l’ordre, segons calgui

R. Martí - 2023/24 30
 Other related functions
htonl(hostlong), htons(hostshort),
ntohl(netlong), ntohs(netshort)
Convert long (32 bit, address)/short (16 bit, port) integers
to/from the standard network representation from/to the
internal host representation.
Often used in conjunction with addresses and ports in struct
hostent returned by gethostbyname(), and in struct
sockaddr_in.
htonl(), htons(): storing to struct hostent/sockaddr_in
ntohl(), ntohs(): reading from struct hostent/sockaddr_in
inet_ntoa(internetaddr)
Converts an IP address to dotted quad string representation.
inet_addr(string)
Converts a dotted quad string IP address to a 32-bit integer.

R. Martí - 2023/24 31
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 32
Behavioral parameters
 Algorithms and issues around the server
 There are three parameters defining the behavior of
client/server applications:
 Iterative/concurrent model.
 Reliability in the application/ in the transport protocol.
 Information servers have about the clients
(stateful/stateless).

R. Martí - 2023/24 33
 Iterative / Concurrent
 Iterative
 Requests are served sequentially, one after the other.
 It is strange to find iterative servers.
 Clients normally are Iterative.
 Concurrent
 Different requests are served simultaneously.
 This concurrency can be performed by duplicating
processes (on request or in advance), or in one process.
 Servers normally are Concurrent (although they
may be iterative).

R. Martí - 2023/24 34
 Reliability in application / in transport
 Reliability
 The TCP protocol already provides reliability.
• Applications using TCP do not need to implement reliability.
• An example of this is a HTTP server.
 Connectionful: Connection oriented protocol
 No Reliability
 UDP does not provide reliability.
• If the application requires reliability it has to implement it.
• An example of this is the TFTP server.
 Connectionless: Datagram oriented protocol
 Implementing reliability in the application is complex.
Generally, UDP is used when no reliability is required.

R. Martí - 2023/24 35
 Stateful / Stateless
 Stateful
 A stateful server is aware of the “state” in which a client
is during a service.
 A stateful server requires to store information about the
connection in order to provide responses to a client.
 Stateless
 A stateless server, does not keep previous information
about a client to provide it with service responses.
 If it is stateless, this state must be provided by the client
in every interaction.

R. Martí - 2023/24 36
 In the case of a file server, for instance, we have:
 With a stateful server:
1. -> The client sends a file read request.
2. <- The server creates an entry in a table with the state.
3. -> The client request the reading of n bytes.
4. <- The server sends those bytes and moves the cursor of
the file in the client state.
5. Steps 3 and 4 are repeated until the file is sent.

 With a stateless server:


1. -> The client sends a file read request, specifying the
name, byte position to read, and offset.
2. <- The server sends the bytes and forgets the request.
3. Steps 1 and 2 are repeated at client’s will.

R. Martí - 2023/24 37
 Issues with stateful servers:
 What happens if the servers crashes or restarts?
 Read operations will fail.
 What happens if the client crashes?
 Entries in the server state table will be obsolete.
 What happens if there is no reliability and duplicated
requests arrive?
 Responses to identical requests may vary.

 Servers with no reliability use to be stateless, like


the TFTP.
 Example of stateless servers: HTTP, DNS servers
 Examples of stateful servers: FTP, Telnet servers

R. Martí - 2023/24 38
 We can have different servers by combining
these features:

TCP (connection) UDP (connectionless)


Iterative Seldom Usual
Concurrent Usual Strange!: Tm>>Ts

 Ts -> Service time per request.


 Tm -> Management time per request.

R. Martí - 2023/24 39
Connectionless iterative server
 In this case Tm ≈ Ts (small).

 Algorithm:
1. Create a socket
2. Bind the socket to a free local address/port
3. Repeat {
Read message from socket (request);
Send message to socket (response) }
4. Close socket

R. Martí - 2023/24 40
Connectionless iterative server
 System calls used:
// socket creation:
sock=socket(PF_INET, SOCK_DGRAM, PROT_UDP)
// local address and port initialization:
// ads -> sockaddr_in
// address=INADDR_ANY
// port=service_port
// Binding of socket to port:
bind(sock, ads)
do {
recvfrom(sock, buffer, client_address)
sendto(sock, message, client_address)
} while (no end)
close(sock) //in case do-while loop exits

R. Martí - 2023/24 41
Connectionful iterative server
 Here we use two sockets.
 One is waiting for connections
 The other serves requests

 Algorithm:
1. Create a socket (psock)
2. Bind psock to a free local address/port
3. Open psock in passive mode (“listen”)
4. Accept a connection, obtaining a new socket csock
5. Repeat {
Read from socket csock (request);
Send to socket csock (response) }
6. Close socket csock.
7. Go to 4.
8. Close socket psock

R. Martí - 2023/24 42
Connectionful iterative server
 System calls used:
psock=socket(PF_INET, SOCK_STREAM, PROT_TCP)
// local address and port initialization
// ads -> sockaddr_in
// address=INADDR_ANY
// port=service_port
bind(psock, ads)
listen(psock, len_waiting_queue)
do {
csock = accept(psock)
do {
read(csock, ...)
write(csock, ...)
} while (no end)
close(csock)
} while (needed)
close(psock)

R. Martí - 2023/24 43
Inicialització d’adreces i ports
 Abans de rebre o enviar dades, cal inicialitzar adreces i ports
 UDP
 “Servidor”: Associar l’adreça i port local on podrà rebre
datagrames
 Abans de bind()
 Adreça, normalment INADDR_ANY
 “Client”: Per dir a quina adreça i port remot s’enviaran els
datagrames
 Abans de sendto()
 TCP
 Servidor: Per associar l’adreça i port local on es posarà a escoltar
 Abans de bind()
 Adreça, normalment INADDR_ANY
 Client: Per dir a quina adreça i port remot es connectarà
 Abans de connect()
 Hi ha diferents maneres correctes d’inicialitzar adreces i ports

R. Martí - 2023/24 44
Addresses and ports initialization
Example 1
 Server (before bind(... localaddr))
struct sockaddr_in server_addr; // localaddr [or destaddr]
...
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(server_addr.sin_zero), sizeof(server_addr.sin_zero));

 Client (before sendto(... serveraddr) / connect(... destaddr ...))


struct hostent *host;
struct sockaddr_in server_addr; // destaddr
...
host = gethostbyname("127.0.0.1"); // or any domainname i.e.
www.uab.cat

server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(5000);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero), sizeof(server_addr.sin_zero));

R. Martí - 2023/24 45
Addresses and ports initialization
Example 2
 Server (before bind(... localaddr))
struct sockaddr_in address_ser; // localaddr [or destaddr]
...
address_ser.sin_family = AF_INET;
address_ser.sin_addr.s_addr = htonl(INADDR_ANY);
address_ser.sin_port = htons(6001);

 Client (before sendto(... serveraddr) / connect(... destaddr ...))


struct hostent *h;
struct sockaddr_in address_ser; // destaddr
...
h = gethostbyname(“localhost”); // any domainname i.e. www.uab.cat

address_ser.sin_family = h->h_addrtype; // or AF_INET;


memcpy((char *) &address_ser.sin_addr.s_addr, h->h_addr_list[0],
h->h_length);
address_ser.sin_port = htons(6001);

R. Martí - 2023/24 46
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 47
 Algorithms and issues around the client
 There can be
 Connectionful iterative client (over TCP)
 Requires total reliability.
 This is provided by the transport layer.
 It is used for long services: three datagrams for connection
establishment and four for termination.
 Connectionless iterative client (over UDP)
 Requires only a relative reliability provided by the application
layer.
 It is used when there is a short service time: the connection is
not justified
 There are no concurrent Clients

R. Martí - 2023/24 48
Connectionful iterative client
 Algorithm:
1. Find IP address and port of the server to contact
2. Create a socket sock.
3. Connect the socket to the server
4. Repeat {
5. Send to socket (request)
6. Read from socket (response)
7. } until application protocol finishes.
8. Close socket

R. Martí - 2023/24 49
Connectionful iterative client
 System calls used:
sock=socket(PF_INET, SOCK_STREAM, PROT_TCP)
... // incl. remote_address initialization
connect(sock, remote_address, ...)
// The connect call involves the three-way
// handshake for the establishment of the
// connection.
do {
write(sock, buffer, length)
nb = read(sock, buffer, length)
} while (needed)
[shutdown(sock, direction)]
close(sock) // total closing

R. Martí - 2023/24 50
Connectionless iterative client
 Algorithm:
1. Find IP address and port of the server to contact
2. Create a socket sock.
3. [Bind the socket to the local IP address and to a
free port.]
4. Repeat {
5. Send to socket (request)
6. Read from socket (response) }
7. Go to 4 unless the application protocol finishes.
8. Close socket.

R. Martí - 2023/24 51
Connectionless iterative client
 System calls used:
sock=socket(PF_INET, SOCK_DGRAM, PROT_UDP)
... // incl. remote [& local] address init.
[bind(sock, local_address,...)] // port=0, ->OS !
...
do {
sendto(sock, message, ..., remote_address)
recvfrom(sock, message, ..., remote_address)
} while (needed)
close(sock)

R. Martí - 2023/24 52
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 53
Connectionful concurrent server

 Connectionful concurrent server


 The server can now process more than one client request
simultaneously.
 On the left, the ideal server is shown.
 The real one is on the right.
 Ts: service time
 Tm: time of creating the process
 Processing, split in time and in processors

R. Martí - 2023/24 54
Connectionful concurrent server
 Concurrent server with processes creation, worth if:
 Multi-processor server with a process in every processor.
 Ts is bigger than Tm.
 Ts are very variable (some very small, some very big).
 In this type of servers we will have a parent process and child
processes.
 fork() is used to create a child process in Unix/Linux:
 pid = fork(void);
 The parent process is in charge of accepting connections and
creating children
 Child processes are in charge of serving concurrently/in parallel
the clients
 Each child, 1 client
 The parent process must be aware of the dying children:
 A Child ‘informs’ parent when it dies
 Parent accepts it, otherwise child will become a zombie.

R. Martí - 2023/24 55
Connectionful concurrent server
 Algorithm of the parent process:
1. Create a socket (psock)
2. Bind psock to a free address/port
3. Open psock in passive mode (“listen”)
4. Accept a connection, obtaining a new socket csock
5. Create a child process to serve the request with csock
6. Close socket csock and go to 3.

 Algorithm of the child process:


1. Close psock
2. Repeat {
Read from socket csock (request);
Send to socket csock (response) }
3. Close socket csock.
4. Die

R. Martí - 2023/24 56
Connectionful concurrent server
... //PARENT
psock=socket(PF_INET, SOCK_STREAM, PROT_TCP)
bind(psock, ads)
listen(psock, len_wait_queue)
do{
csock=accept(psock)
child_pid=fork() //create_child
if (child_pid==0){ //child receives 0
child(); //parent receives child process id
exit();
}
close(csock);
} while(true)
...

child( //CHILD
close(psock); //code could go inside main function
do { //instead of call to child()
read(csock, ...)
write(csock, ...)
} while (no end)
close(csock)
};

R. Martí - 2023/24 57
Connectionful concurrent server
with one process
 In this type of servers there is only one process
serving concurrently all requests from clients.
 -> It is useful when there are many clients
requesting the same.
 -> If there is a high client activity, the performance
of the server drops quickly.

 The select() system call is used to detect socket


activity.
 Sockets available to send or sockets with data received are
detected
 Then, those can be accessed -> no blocking, to send and
receive respectively

R. Martí - 2023/24 58
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 Què hem après?
 El model client/servidor.
 Diferents models de comunicació distribuïda.
 Les bases de la programació d’aplicacions
distribuïdes mitjançant sockets, com a base de la
primera pràctica de l’assignatura.

R. Martí - 2023/24 59
Additional Slides
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 61
Middleware
 Sometimes, difficult to integrate multiple clients and servers
from multiple vendors -> different standards
 One solution: Middleware:
 Software between or in the middle of any of the 3 application levels
 On client and/or server
 “Connects” layers with complementary functionality & different
interfaces

 Software that enables communication and management of data


in distributed applications.
 Dash in 'client-server‘, or '-to-' in peer-to-peer
 Middleware does two things:
1. It provides a standard way of communicating that can translate
between software from different vendors.
2. It manages the message transfer from clients to servers so that the
clients need not know the specific server that contains the application’s
data.

R. Martí - 2023/24 62
Middleware
 E.g. between Application Logic

Interface
Processing

Middleware
Processing

Data

R. Martí - 2023/24 63
Middleware
 Exemples:
 Enmig de nivell:

 Entre nivells:

R. Martí - 2023/24 64
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 65
gethostbyname(namestr)
To get information of a host (name, address, …) from its domain
name.
getpeername(socket, destaddr, addrlen)
To know the address of the destination socket which we are
connected.

getsockname(socket, localaddr, addrlen)


Address of the local socket.
getsockopt(soc, level, optid, optval, length)
To obtain information from a socket.
setsockopt(soc, level, optid, optval, length)
To modify the options of a socket.
gethostbyaddr(addr, len, type)
To get information of a host (name, address, …) from its address.

R. Martí - 2023/24 66
getprotobyname(name)
To get information of a protocol from its name.
getprotobynumber(number)
To get the same protocol information, but from the
identifying number.
getservbyname(name, proto)
To get service information from its name.
getservbyport(port, proto)
Exactly the same service information, but from the
number of port.

R. Martí - 2023/24 67
result = socket(pf, type, prot)
int socket(int pf, int type, int prot);
Creates a socket.
result -> Descriptor for identifying the socket.
pf -> Protocol family (e.g. PF_INET: TCP/IP, PF_PUP: Xerox,
PF_UNIX: Unix).
type -> Type of communication:
SOCK_STREAM Connection oriented service using a stream.
SOCK_DGRAM Connectionless datagrams.
SOCK_RAW For directly accessing the interface.
prot -> Specific protocol for the transmission.

R. Martí - 2023/24 68
close(socket)
int close(int socket);
Decreases the reference counter associated with the
socket.
If the counter reaches zero, the socket is destroyed.

bind(socket, localaddr, addrlen)


int bind(int socket, const struct sockaddr
*localaddr, socklen_t addrlen);
Binds a socket to a port.
socket -> Descriptor of the socket.
localaddr -> Local end point for binding to the socket.
addrlen -> Number of bytes of the end point.

R. Martí - 2023/24 69
connect(socket, destaddr, addrlen)
int connect(int socket, const struct
sockaddr *destaddr, socklen_t addrlen);
Establishes a connection.
If the socket uses a connectionless service this system call
is used to store addresses.
destaddr -> End point of the remote address of the connection.
addrlen -> Number of bytes of the end point.

shutdown(socket, mode)
int shutdown(int socket, int mode);
Partially closes the bidirectional connection.
mode -> Which direction is closed.

R. Martí - 2023/24 70
send(sock, message, length, flags)
ssize_t send(int sock, const void *message, size_t
length, int flags);
Sends data through a connected socket.
message -> Pointer to the data to be sent.
flags -> Options for the transmission control.

sendto(sock, message, length, flags, destaddr,


addrlen)
ssize_t sendto(int sock, const void *message, size_t
length, int flags, const struct sockaddr
*destaddr, socklen_t *addrlen);
Sends data through a connectionless socket.
destaddr -> Pointer to the structure with the remote address.
addrlen -> Length of the address.

R. Martí - 2023/24 71
recv(sock, buffer, length, flags)
ssize_t recv(int sock, void *buffer, size_t length,
int flags);
Receives data from a connected socket.
flags -> For the control of the reception.
Example: option for accessing received data without emptying the buffer.

recvfrom(sock, buffer, length, flags, fromaddr,


addrlen)
ssize_t recvfrom(int sock, void *buffer, size_t
length, int flags, struct sockaddr *fromaddr,
socklen_t *addrlen);
Receives data from a connectionless socket.
fromaddr -> Source address of the received data.

R. Martí - 2023/24 72
write(socket, buffer, length)
ssize_t write(int socket, const void
*buffer, size_t length);
Writes data to a connected socket.
buffer -> Pointer to the data to be sent.
addrlen -> Number of bytes to send.

read(socket, buffer, length)


ssize_t read(int socket, void * buffer,
size_t length);
Reads data from a connected socket.
buffer -> Pointer where data will be stored.
length -> Number of bytes to be read.

R. Martí - 2023/24 73
listen(socket, qlength)
int listen(int socket, int qlength);
Prepares a socket for receiving connection (passively
opens connections).
This is only used with stream oriented sockets.
qlength -> Length of the request queue.

newsock = accept(socket, addr, addrlen)


int accept(int socket, struct sockaddr
*addr, socklen_t *addrlen);
Accepts a new connection.
addr -> Address of the requesting client.
newsock -> New socket created by the system and connected to
the client.

R. Martí - 2023/24 74
gethostbyname(name);
struct hostent *gethostbyname(const char *name);
Returns a structure of type hostent for the given host name.
name -> either a host name, or an IPv4 address in standard dot notation, or an IPv6 address in
colon (and possibly dot) notation.
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
}
#define h_addr h_addr_list[0] /* for backward compatibility */
 The members of the hostent structure are:
h_name -> The official name of the host.
h_aliases -> An array of alternative names for the host, terminated by a NULL pointer.
h_addrtype -> The type of address; always AF_INET or AF_INET6 at present.
h_length -> The length of the address in bytes.
h_addr_list -> An array of pointers to network addresses for the host (in network byte
order), terminated by a NULL pointer.
h_addr -> The first address in h_addr_list for backward

R. Martí - 2023/24 75
htonl(hostlong), htons(hostshort),
ntohl(netlong), ntohs(netshort)
uint32_t htonl(uint32_t hostlong),
uint16_t htons(uint16_t hostshort),
uint32_t ntohl(uint32_t netlong),
uint16_t ntohs(uint16_t netshort)
Convert long (32 bit, address)/short (16 bit, port) integers to/from the standard
network representation from/to the internal host representation.
htonl() converts the unsigned integer hostlong from host byte order to network byte order.
htons() converts the unsigned short integer hostshort from host byte order to network
byte order.
ntohl() converts the unsigned integer netlong from network byte order to host byte order.
ntohs() converts the unsigned short integer netshort from network byte order to host byte
order.
On machines which have a byte order which is the same as the network order, routines
are defined as null macros.
Often used in conjunction with addresses and ports in struct hostent returned by
gethostbyname(), and in struct sockaddr_in.

R. Martí - 2023/24 76
in_addr_t inet_addr(const char *cp);
Converts the Internet host address cp from IPv4 numbers-
and-dots notation into binary data in network byte
order.
typedef uint32_t in_addr_t;

char *inet_ntoa(struct in_addr in);


Converts the Internet host address in, given in network
byte order, to a string in IPv4 dotted-decimal notation.
The string is returned in a statically allocated buffer, which
subsequent calls will overwrite.
struct in_addr {
in_addr_t s_addr;
};

R. Martí - 2023/24 77
I.3 Capa d'Aplicació: Aplicacions i
serveis distribuïts
 I.3.1 Arquitectura client / servidor
 I.3.2 Models de comunicació distribuïda
 RPC
 RMI
 Paquets/Datagrames
 Fluxos
 Missatges
 Web services
 Nous paradigmes
 I.3.3 Programació d'aplicacions distribuïdes
 Sockets
 Servidors
 Clients
 Servidors concurrents

R. Martí - 2023/24 78
pid = fork(void)
pid_t fork(void);
Creates a child process that differs from the
parent process only in its PID and PPID, and in
the fact that resource utilizations are set to 0.
File locks and pending signals are not inherited.
pid -> On success, the PID of the child process is
returned in the parent's thread of execution, and a
0 is returned in the child's thread of execution. On
failure, a -1 will be returned in the parent's context,
no child process will be created, and errno will be set
appropriately.

R. Martí - 2023/24 79
nready = select(ndesc, indesc, outdesc,
excdesc, timeout)
int select(int ndesc, fd_set *indesc,
fd_set *outdesc, fd_set *excdesc, struct
timeval *timeout)
Indicates whether data is already available from a socket,
or if a timeout with no activity in the socket has expired.
nready -> Number of descriptors that are ready.
ndesc -> Number of descriptors to probe.
indesc, outdesc, escdesc -> Pointer to a bit mask
specifying the descriptors to probe in the input, output, or
exception conditions.
timeout -> Time to wait for coming data.
If it is zero, it waits for ever.

R. Martí - 2023/24 80
Connectionful concurrent server
with one process
 Algorithm:
1. Create a socket (msock) and bind it to an address/port
2. Open the socket in passive mode
3. Set the msock in the control list
4. Repeat {
5. Select
6. If there is activity in msock create a new socket ssock and
add it to the list.
7. For each ssock socket do
8. If there is activity in ssock { Read and write }
9. Finish and delete the ssocks from the list if needed
10.Go to 4.

R. Martí - 2023/24 81
Connectionful concurrent server
with one process
 System calls used:
msock=socket(...); bind(...); listen(...);
FD_ZERO(list );
FD_SET( msock, list);
do {ret = select( ..., list, ...)
if FD_ISSET(msock, list) {
ssock = accept(msock);
FD_SET(ssock, list) }
for i in list {
if FD_ISSET(i, list) {
read(ssock);
write(ssock) }
if end_service(i) {
close(ssock);
FD_CLEAR(ssock,...) }}
} while(true)

R. Martí - 2023/24 82

You might also like