3rd Edition: Chapter 2

Download Report

Transcript 3rd Edition: Chapter 2

Chapter 2
Application Layer
Http
Thanks and enjoy! JFK/KWR
All material copyright 1996-2005
J.F Kurose and K.W. Ross, All Rights Reserved
Computer Networking:
A Top Down Approach
Featuring the Internet,
3rd edition.
Jim Kurose, Keith Ross
Addison-Wesley, July
2004.
2: Application Layer
1
Chapter 2: Application layer
 2.1 Principles of
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail

SMTP, POP3, IMAP
 2.5 DNS
 2.6 P2P file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
2: Application Layer
2
Chapter 2: Application Layer
Our goals:
 conceptual,
implementation
aspects of network
application protocols
 transport-layer
service models
 client-server
paradigm

peer-to-peer
paradigm
 learn about protocols
by examining popular
application-level
protocols




HTTP
FTP
SMTP / POP3 / IMAP
DNS
 programming network
applications

socket API
2: Application Layer
3
Some network apps
 E-mail
 Internet telephone
 Web
 Real-time video
 Instant messaging
 Remote login
 P2P file sharing
 Multi-user network
games
 Streaming stored
video clips
conference
 Massive parallel
computing



2: Application Layer
4
Creating a network app
Write programs that



run on different end
systems and
communicate over a
network.
e.g., Web: Web server
software communicates
with browser software
application
transport
network
data link
physical
application
transport
network
data link
physical
application
transport
network
data link
physical
2: Application Layer
5
Chapter 2: Application layer
 2.1 Principles of
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail

SMTP, POP3, IMAP
 2.5 DNS
 2.6 P2P file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
2: Application Layer
6
Application architectures
 Client-server
 Peer-to-peer (P2P)
 Hybrid of client-server and P2P
2: Application Layer
7
Client-server architecture
server:



always-on host
permanent IP address
server farms for scaling
clients:




communicate with
server
may be intermittently
connected
may have dynamic IP
addresses
do not communicate
directly with each other
2: Application Layer
8
Pure P2P architecture
 no always-on server
 arbitrary end systems
directly communicate
 peers are intermittently
connected and change IP
addresses
 example: Gnutella
Highly scalable
But difficult to manage
2: Application Layer
9
Hybrid of client-server and P2P
Napster
File transfer P2P
 File search centralized:

• Peers register content at central server
• Peers query same central server to locate content
Instant messaging
Chatting between two users is P2P
 Presence detection/location centralized:

• User registers its IP address with central server
when it comes online
• User contacts central server to find IP addresses of
buddies
2: Application Layer
10
Processes communicating
Process: program running
within a host.
 within same host, two
processes communicate
using inter-process
communication (defined
by OS).
 processes in different
hosts communicate by
exchanging messages
Client process: process
that initiates
communication
Server process: process
that waits to be
contacted
 Note: applications with
P2P architectures have
client processes &
server processes
2: Application Layer
11
Sockets
 process sends/receives
messages to/from its
socket
 socket analogous to door


sending process shoves
message out door
sending process relies on
transport infrastructure
on other side of door which
brings message to socket
at receiving process
host or
server
host or
server
process
controlled by
app developer
process
socket
socket
TCP with
buffers,
variables
Internet
TCP with
buffers,
variables
controlled
by OS
 API: (1) choice of transport protocol; (2) ability to fix
a few parameters (lots more on this later)
2: Application Layer
12
Addressing processes
 For a process to
receive messages, it
must have an identifier
 A host has a unique32bit IP address
 Q: does the IP address
of the host on which
the process runs
suffice for identifying
the process?
 Answer: No, many
processes can be
running on same host
 Identifier includes
both the IP address
and port numbers
associated with the
process on the host.
 Example port numbers:


HTTP server: 80
Mail server: 25
 More on this later
2: Application Layer
13
App-layer protocol defines
 Types of messages
exchanged, e.g., request
& response messages
 Syntax of message
types: what fields in
messages & how fields
are delineated
 Semantics of the fields,
i.e., meaning of
information in fields
 Rules for when and how
processes send &
respond to messages
Public-domain protocols:
 defined in RFCs
 allows for
interoperability
 e.g., HTTP, SMTP
Proprietary protocols:
 e.g., KaZaA
2: Application Layer
14
What transport service does an app need?
Data loss
 some apps (e.g., audio) can
tolerate some loss
 other apps (e.g., file
transfer, telnet) require
100% reliable data
transfer
Timing
 some apps (e.g.,
Internet telephony,
interactive games)
require low delay to be
“effective”
Bandwidth
 some apps (e.g.,
multimedia) require
minimum amount of
bandwidth to be
“effective”
 other apps (“elastic
apps”) make use of
whatever bandwidth
they get
2: Application Layer
15
Transport service requirements of common apps
Data loss
Bandwidth
Time Sensitive
file transfer
e-mail
Web documents
real-time audio/video
no loss
no loss
no loss
loss-tolerant
no
no
no
yes, 100’s msec
stored audio/video
interactive games
instant messaging
loss-tolerant
loss-tolerant
no loss
elastic
elastic
elastic
audio: 5kbps-1Mbps
video:10kbps-5Mbps
same as above
few kbps up
elastic
Application
yes, few secs
yes, 100’s msec
yes and no
2: Application Layer
16
Internet transport protocols services
TCP service:





connection-oriented: setup
required between client and
server processes
reliable transport between
sending and receiving process
flow control: sender won’t
overwhelm receiver
congestion control: throttle
sender when network
overloaded
does not provide: timing,
minimum bandwidth
guarantees
UDP service:
 unreliable data transfer
between sending and
receiving process
 does not provide:
connection setup,
reliability, flow control,
congestion control, timing,
or bandwidth guarantee
Q: why bother? Why is
there a UDP?
2: Application Layer
17
Internet apps: application, transport protocols
Application
e-mail
remote terminal access
Web
file transfer
streaming multimedia
Internet telephony
Application
layer protocol
Underlying
transport protocol
SMTP [RFC 2821]
Telnet [RFC 854]
HTTP [RFC 2616]
FTP [RFC 959]
proprietary
(e.g. RealNetworks)
proprietary
(e.g., Vonage,Dialpad)
TCP
TCP
TCP
TCP
TCP or UDP
typically UDP
2: Application Layer
18
Chapter 2: Application layer
 2.1 Principles of
network applications


app architectures
app requirements
 2.2 Web and HTTP
 2.4 Electronic Mail
 SMTP, POP3, IMAP
 2.5 DNS
 2.6 P2P file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
2: Application Layer
19
Web and HTTP
First some jargon
 Web page consists of objects
 Object can be HTML file, JPEG image, Java
applet, audio file,…
 Web page consists of base HTML-file which
includes several referenced objects
 Each object is addressable by a URL
 Example URL:
www.someschool.edu/someDept/pic.gif
host name
path name
2: Application Layer
20
HTTP overview
HTTP: hypertext
transfer protocol
 Web’s application layer
protocol
 client/server model
 client: browser that
requests, receives,
“displays” Web objects
 server: Web server
sends objects in
response to requests
 HTTP 1.0: RFC 1945
 HTTP 1.1: RFC 2068
PC running
Explorer
Server
running
Apache Web
server
Mac running
Navigator
2: Application Layer
21
HTTP overview (continued)
Uses TCP:
 client initiates TCP
connection (creates socket)
to server, port 80
 server accepts TCP
connection from client
 HTTP messages (applicationlayer protocol messages)
exchanged between browser
(HTTP client) and Web
server (HTTP server)
 TCP connection closed
HTTP is “stateless”
 server maintains no
information about
past client requests
aside
Protocols that maintain
“state” are complex!
 past history (state) must
be maintained
 if server/client crashes,
their views of “state” may
be inconsistent, must be
reconciled
2: Application Layer
22
HTTP connections
Nonpersistent HTTP
 At most one object is
sent over a TCP
connection.
 HTTP/1.0 uses
nonpersistent HTTP
Persistent HTTP
 Multiple objects can
be sent over single
TCP connection
between client and
server.
 HTTP/1.1 uses
persistent connections
in default mode
2: Application Layer
23
Nonpersistent HTTP
(contains text,
Suppose user enters URL
references to 10
www.someSchool.edu/someDepartment/home.index
jpeg images)
1a. HTTP client initiates TCP
connection to HTTP server
(process) at
www.someSchool.edu on port 80
2. HTTP client sends HTTP
request message (containing
URL) into TCP connection
socket. Message indicates
that client wants object
someDepartment/home.index
1b. HTTP server at host
www.someSchool.edu waiting
for TCP connection at port 80.
“accepts” connection, notifying
client
3. HTTP server receives request
message, forms response
message containing requested
object, and sends message
into its socket
time
2: Application Layer
24
Nonpersistent HTTP (cont.)
4. HTTP server closes TCP
5. HTTP client receives response
connection.
message containing html file,
displays html. Parsing html
file, finds 10 referenced jpeg
objects
time 6. Steps 1-5 repeated for each
of 10 jpeg objects
2: Application Layer
25
Response time modeling
Definition of RRT: time to
send a small packet to
travel from client to
server and back.
Response time:
 one RTT to initiate TCP
connection
 one RTT for HTTP
request and first few
bytes of HTTP response
to return
 file transmission time
total = 2RTT+transmit time
initiate TCP
connection
RTT
request
file
time to
transmit
file
RTT
file
received
time
time
2: Application Layer
26
Persistent HTTP
Nonpersistent HTTP issues:
 requires 2 RTTs per object
 OS overhead for each TCP
connection
 browsers often open parallel
TCP connections to fetch
referenced objects
Persistent HTTP
 server leaves connection
open after sending response
 subsequent HTTP messages
between same client/server
sent over open connection
Persistent without pipelining:
 client issues new request
only when previous
response has been received
 one RTT for each
referenced object
Persistent with pipelining:
 default in HTTP/1.1
 client sends requests as
soon as it encounters a
referenced object
 as little as one RTT for all
the referenced objects
2: Application Layer
27
HTTP request message
 two types of HTTP messages:
request, response
 HTTP request message:
 ASCII (human-readable format)
request line
(GET, POST,
HEAD commands)
GET /somedir/page.html HTTP/1.1
Host: www.someschool.edu
User-agent: Mozilla/4.0
header Connection: close
lines Accept-language:fr
Carriage return,
line feed
indicates end
of message
(extra carriage return, line feed)
2: Application Layer
28
HTTP request message: general format
2: Application Layer
29
Uploading form input
Post method:
 Web page often
includes form input
 Input is uploaded to
server in entity body
URL method:
 Uses GET method
 Input is uploaded in
URL field of request
line:
www.somesite.com/animalsearch?monkeys&banana
2: Application Layer
30
Method types
HTTP/1.0
 GET
 POST
 HEAD

asks server to leave
requested object out of
response
HTTP/1.1
 GET, POST, HEAD
 PUT

uploads file in entity
body to path specified
in URL field
 DELETE
 deletes file specified in
the URL field
2: Application Layer
31
Exemple POST
POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
2: Application Layer
32
POST
 dans une requête POST il n'y a pas qu'un
entête: les données sont dans le corps du
message
 les données définissent des variables qui
seront utilisées par le CGI
 l'url requise est normalement un
programme
 la réponse HTTP est normalement la sortie
d'un programme
2: Application Layer
33
HTTP response message
status line
(protocol
status code
status phrase)
header
lines
data, e.g.,
requested
HTML file
HTTP/1.1 200 OK
Connection close
Date: Thu, 06 Aug 1998 12:00:15 GMT
Server: Apache/1.3.0 (Unix)
Last-Modified: Mon, 22 Jun 1998 …...
Content-Length: 6821
Content-Type: text/html
data data data data data ...
2: Application Layer
34
HTTP response status codes
In first line in server->client response message.
A few sample codes:
200 OK

request succeeded, requested object later in this message
301 Moved Permanently

requested object moved, new location specified later in
this message (Location:)
400 Bad Request

request message not understood by server
404 Not Found

requested document not found on this server
505 HTTP Version Not Supported
2: Application Layer
35
Trying out HTTP (client side) for yourself
1. Telnet to your favorite Web server:
telnet cis.poly.edu 80
Opens TCP connection to port 80
(default HTTP server port) at cis.poly.edu.
Anything typed in sent
to port 80 at cis.poly.edu
2. Type in a GET HTTP request:
GET /~ross/ HTTP/1.1
Host: cis.poly.edu
By typing this in (hit carriage
return twice), you send
this minimal (but complete)
GET request to HTTP server
3. Look at response message sent by HTTP server!
2: Application Layer
36
Méthodes http

GET


HEAD







C'est la méthode la plus courante pour demander une ressource. Une requête GET
est sans effet sur la ressource, il doit être possible de répéter la requête sans
effet.
Cette méthode ne demande que des informations sur la ressource, sans demander
la ressource elle-même.
POST

Cette méthode doit être utilisée lorsqu'une requête modifie la ressource.

Cette méthode permet d'obtenir les options de communication d'une ressource ou
du serveur en général.
OPTIONS
CONNECT

Cette méthode permet d'utiliser un proxy comme un tunnel de communication.

Cette méthode demande au serveur de retourner ce qu'il a reçu, dans le but de
tester et effectuer un diagnostic sur la connexion.
TRACE
PUT

Cette méthode permet d'ajouter une ressource sur le serveur.

Cette méthode permet de supprimer une ressource du serveur.
DELETE
2: Application Layer
37
entêtes

Host


Referer





Indique l'URI du document qui a donné un lien sur la ressource demandée. Cet entête permet aux webmasters d'observer d'où viennent les visiteurs.
User-Agent


Permet de préciser le site Web concerné par la requête, ce qui est nécessaire
pour un serveur hébergeant plusieurs sites à la même adresse IP (name based
virtual host, hôte virtuel basé sur le nom). (Obligatoire)
Indique le logiciel utilisé pour se connecter. Il s'agit généralement d'un navigateur
Web ou d'un robot d'indexation.
Connection

connection persistante ou non

Cet en-tête liste les types MIME de contenu acceptés par le client. Le caractère
étoile * peut servir à spécifier tous les types / sous-types.
Accept
Accept-Charset

Spécifie les encodages de caractères acceptés.

Spécifie les langages acceptés.
Accept-Language
2: Application Layer
38
Réponses
 Date

Moment auquel le message est généré.

Indique quel modèle de serveur HTTP répond à la requête.

Indique la taille en octets de la ressource.

Indique le type MIME de la ressource.
 Server
 Content-Length
 Content-Type
 Expires

Indique le moment après lequel la ressource devrait être
considérée obsolète ; permet aux navigateurs Web de
déterminer jusqu'à quand garder la ressource en mémoire
cache.
 Last-Modified

Indique la date de dernière modification de la ressource
demandée.
2: Application Layer
39
Let’s look at HTTP in action
 telnet example
 Ethereal example
2: Application Layer
40
CGI
 Common Gateway Interface
 exécuter du code du côté serveur
 Passage de paramètre par la méthode
POST ou la méthode GET
 Variables d'environnement
2: Application Layer
41
Exemple
 en shell: date.cgi
#!/bin/sh
tmp=`/bin/date`
cat << ! Content-type: text/html
<HTML><HEAD><TITLE>Script
Cgi</TITLE></HEAD> <BODY> <CENTER>
<H1>La date courante sur le serveur
est</H1> $tmp </CENTER> </BODY> </HTML>
!
 l'URL affichera la date
2: Application Layer
42
Avec un formulaire:
<HTML><HEAD><TITLE>Formulaire simple</TITLE></HEAD>
<BODY>
<H2>Répondez aux questions suivantes</H2>
<FORM ACTION="http://www.monsite.com/cgi-bin/treat.pl"
METHOD=GET>
Prénom : <INPUT TYPE="text" NAME=prenom SIZE=20><BR>
Nom : <INPUT TYPE="text" NAME=nom SIZE=20><BR>
Age : <SELECT NAME=age>
<OPTION>- de 18 ans
<OPTION>19 à 40 ans
<OPTION>41 à 60 ans
<OPTION>+ de 60 ans
</SELECT><BR>
<INPUT TYPE=submit VALUE="Envoyer"> <INPUT TYPE=reset
VALUE="Remettre
à zéro">
</FORM>
</BODY>
2: Application Layer
43
Résultat
 par la méthode get codage des paramètres:
 prenom=Hugues&nom=Fauconnier&age=
41+%E0+60+ans
 le navigateur génère l'url:
http://www.monsite.com/cgibin/treat.pl?prenom=Hugues&nom=Fauconnier&age=41+
%E0+60+ans
 Avec la méthode POST
http://www.monsite.com/cgi-bin/treat.pl
prenom=Hugues&nom=Fauconnier&age=41
2: Application Layer
44
Traitement en perl
 fichier perl
2: Application Layer
45
Paramètres
 Les paramètres sont accessibles par
l'intermédiaire de la variable
d'environnement QUERY_STRING
2: Application Layer
46
Variables d'environnement
 SERVER_SOFTWARE

Le nom et la version du serveur HTTP répondant
à la requête. (Format : nom/version)
 SERVER_NAME

Le nom d'hôte, alias DNS ou adresse IP du
serveur.
 GATEWAY_INTERFACE

La révision de la spécification CGI que le
serveur utilise. (Format : CGI/révision)
2: Application Layer
47
Variables…
 SERVER_PROTOCOL

Le nom et la révision du protocole dans lequel la requête a été
faite (Format : protocole/révision)
 SERVER_PORT

Le numéro de port sur lequel la requête a été envoyée.

La méthode utilisée pour faire la requête. Pour HTTP, elle
contient généralement « GET » ou « POST ».
 REQUEST_METHOD
 PATH_INFO

Le chemin supplémentaire du script tel que donné par le client.
Par exemple, si le serveur héberge le script « /cgibin/monscript.cgi » et que le client demande l'url «
http://serveur.org/cgi-bin/monscript.cgi/marecherche », alors
PATH_INFO contiendra « marecherche ».
 PATH_TRANSLATED

Contient le chemin demandé par le client après que les
conversions virtuel → physique aient été faites par le serveur.
2: Application Layer
48
Variables
 SCRIPT_NAME

Le chemin virtuel vers le script étant exécuté. Exemple : « /cgibin/script.cgi »
 QUERY_STRING

Contient tout ce qui suit le « ? » dans l'URL envoyée par le
client. Toutes les variables provenant d'un formulaire envoyé
avec la méthode « GET » sera contenue dans le
QUERY_STRING sous la forme « var1=val1&var2=val2&... ».
 REMOTE_HOST

Le nom d'hôte du client. Si le serveur ne possède pas cette
information (par exemple, lorsque la résolution DNS inverse est
désactivée), REMOTE_HOST sera vide.
 REMOTE_ADDR

L'adresse IP du client.

Le type d'identification utilisé pour protéger le script (s’il est
protégé et si le serveur supporte l'identification).
 AUTH_TYPE
2: Application Layer
49
Variables
 AUTH_TYPE

Le type d'identification utilisé pour protéger le script (s’il est
protégé et si le serveur supporte l'identification).
 REMOTE_USER

Le nom d'utilisateur du client, si le script est protégé et si le
serveur supporte l'identification.
 REMOTE_IDENT

Nom d'utilisateur (distant) du client faisant la requête. Le
serveur doit supporter l'identification RFC 931. Cette variable
devraient être utilisée à des fins de journaux seulement.
 CONTENT_TYPE

Le type de contenu attaché à la requête, si des données sont
attachées (comme lorsqu'un formulaire est envoyé avec la
méthode « POST »).
 CONTENT_LENGTH

La longueur du contenu envoyé par le client.
2: Application Layer
50
Variables
 HTTP_ACCEPT
• Les types de données MIME que le client
accepte de recevoir.
• Exemple : text/*, image/jpeg, image/png,
image/*, */*
 HTTP_ACCEPT_LANGUAGE
• Les langages dans lequel le client accepte
de recevoir la réponse.
• Exemple : fr_CA, fr
 HTTP_USER_AGENT
• Le navigateur utilisé par le client.
• Exemple : Mozilla/5.0 (compatible;
Konqueror/3; Linux)
2: Application Layer
51
User-server state: cookies
Many major Web sites
use cookies
Four components:
1) cookie header line of
HTTP response message
2) cookie header line in
HTTP request message
3) cookie file kept on
user’s host, managed by
user’s browser
4) back-end database at
Web site
Example:



Susan access Internet
always from same PC
She visits a specific ecommerce site for first
time
When initial HTTP
requests arrives at site,
site creates a unique ID
and creates an entry in
backend database for
ID
2: Application Layer
52
Cookies: keeping “state” (cont.)
client
Cookie file
server
usual http request msg
usual http response +
ebay: 8734
Cookie file
amazon: 1678
ebay: 8734
Set-cookie: 1678
usual http request msg
cookie: 1678
usual http response msg
one week later:
Cookie file
amazon: 1678
ebay: 8734
usual http request msg
cookie: 1678
usual http response msg
server
creates ID
1678 for user
cookiespecific
action
cookiespectific
action
2: Application Layer
53
Cookies (continued)
What cookies can bring:
 authorization
 shopping carts
 recommendations
 user session state
(Web e-mail)
aside
Cookies and privacy:
 cookies permit sites to
learn a lot about you
 you may supply name
and e-mail to sites
 search engines use
redirection & cookies
to learn yet more
 advertising companies
obtain info across
sites
2: Application Layer
54
Web caches (proxy server)
Goal: satisfy client request without involving origin server
 user sets browser: Web
accesses via cache
 browser sends all HTTP
requests to cache


object in cache: cache
returns object
else cache requests
object from origin
server, then returns
object to client
origin
server
client
client
Proxy
server
origin
server
2: Application Layer
55
More about Web caching
 Cache acts as both client
and server
 Typically cache is installed
by ISP (university,
company, residential ISP)
Why Web caching?
 Reduce response time for
client request.
 Reduce traffic on an
institution’s access link.
 Internet dense with caches
enables “poor” content
providers to effectively
deliver content (but so
does P2P file sharing)
2: Application Layer
56
Caching example
Assumptions
 average object size = 100,000
bits
 avg. request rate from
institution’s browsers to origin
servers = 15/sec
 delay from institutional router
to any origin server and back
to router = 2 sec
Consequences
origin
servers
public
Internet
1.5 Mbps
access link
institutional
network
10 Mbps LAN
 utilization on LAN = 15%
 utilization on access link = 100%
 total delay
= Internet delay +
access delay + LAN delay
= 2 sec + minutes + milliseconds
institutional
cache
2: Application Layer
57
Caching example (cont)
Possible solution
 increase bandwidth of access
link to, say, 10 Mbps
Consequences
origin
servers
public
Internet
 utilization on LAN = 15%
 utilization on access link = 15%
= Internet delay +
access delay + LAN delay
= 2 sec + msecs + msecs
 often a costly upgrade
10 Mbps
access link
 Total delay
institutional
network
10 Mbps LAN
institutional
cache
2: Application Layer
58
Caching example (cont)
origin
servers
Install cache
 suppose hit rate is .4
Consequence
public
Internet
 40% requests will be
satisfied almost immediately
 60% requests satisfied by
origin server
 utilization of access link
reduced to 60%, resulting in
negligible delays (say 10
msec)
 total avg delay = Internet
delay + access delay + LAN
delay = .6*(2.01) secs +
milliseconds < 1.4 secs
1.5 Mbps
access link
institutional
network
10 Mbps LAN
institutional
cache
2: Application Layer
59
Conditional GET
 Goal: don’t send object if
cache has up-to-date cached
version
 cache: specify date of
cached copy in HTTP request
If-modified-since:
<date>
 server: response contains no
object if cached copy is upto-date:
HTTP/1.0 304 Not
Modified
server
cache
HTTP request msg
If-modified-since:
<date>
HTTP response
object
not
modified
HTTP/1.0
304 Not Modified
HTTP request msg
If-modified-since:
<date>
HTTP response
object
modified
HTTP/1.0 200 OK
<data>
2: Application Layer
60
Compléments Javascript
 Code qui s'exécute du côté du client
calcul local
 contrôle d'une zone de saisie
 affichage d'alerte
 fenêtres menus etc..

 Balise :
<SCRIPT languge="JavaScript1.2">
le code...
</SCRIPT>
2: Application Layer
61
Exemple: bonjour
<HTML><HEAD>
<TITLE>Très facile</TITLE>
</HEAD>
<SCRIPT language="JavaScript1.2">
function bonjour()
{
alert ("Bonjour madame, bonjour monsieur");
}
</SCRIPT>
<BODY bgcolor="WHITE" onLoad="bonjour();">
<H1>Bonjour</H1>
</BODY></HTML>
2: Application Layer
62
Un peu plus: minicalcul
HTML>
<HEAD>
<TITLE>Petit calcul</TITLE>
</HEAD>
<BODY bgcolor='WHITE'>
<script language='JavaScript1.2' src='calcul.js'></script>
<script language='JavaScript1.2' src='fenetre.js'></script>
<script language='JavaScript1.2' src='ctrl.js'></script>
<CENTER><H1>Calcul</H1></CENTER>
Un petit exemple de formulaire.
<P>
Création d'une
<A href='#A' onClick='afficheDoc();'>fenêtre avec JavaScript</A>
2: Application Layer
63
Suite
<FORM ACTION='Simul.html' METHOD='POST' NAME='Simul'>
<CENTER>
<TABLE BORDER=3>
<TR><TD>Argument 1
<TD> <INPUT TYPE='TEXT' SIZE=20 NAME='arg1' onChange='calcul();'></TR>
<TR><TD>* Argument 2
<TD> <INPUT TYPE='TEXT' SIZE=20
NAME='arg2' onChange='calcul();'>
</TR>
<TR><TD>Résultat=
<TD> <INPUT TYPE='TEXT' SIZE=20
NAME='res' >
</TR>
</TABLE>
<INPUT TYPE='BUTTON' VALUE='Vérifier' onClick='ctrl();'>
<INPUT TYPE='RESET' VALUE='Effacer tout'
onClick=' if (!confirm("Vraiment vous voulez effacer ?")) exit;'>
</CENTER>
</FORM>
</BODY>
</HTML>
2: Application Layer
64
Fichiers js
 ctrl.js calcul
function ctrl()
{
if (isNaN(window.document.Simul.res.value ))
{
alert ("Valeur incorrecte : " +
document.Simul.res.value + "?");
document.forms[0].res.focus();
}
}
function calcul()
{
v1=document.forms[0].arg1.value;
v2=document.forms[0].arg2.value;
document.forms[0].res.value = v2*v1 ;
}
2: Application Layer
65
suite et fin
 fenetre.js
function afficheDoc()
{
options = "width=300,height=200";
fenetre = window.open('','MU',options);
fenetre.document.open();
manuel =
"<HTML><HEAD><TITLE>Documentation</TITLE></HEAD>"
+ "<BODY bgcolor='white'>"
+ "Il n'y a pas besoin d'aide "
+ " c'est facile."
+ " Bonne chance !</BODY></HTML>";
fenetre.document.write(manuel);
fenetre.document.close();
}
2: Application Layer
66
Compléments: php
 php est un langage de script pour les
serveurs webs
 de nombreuses fonctions permettent de
traiter les requêtes http
 ici on est du côté du serveur…
2: Application Layer
67
Exemple simple
<HTML> <HEAD>
<TITLE>Exemple très simple</TITLE>
</HEAD>
<BODY>
<H1>Exemple</H1>
le <?php echo Date ("j/m/Y à H:i:s"); ?>
<P>
<?php
echo "Client :" . $_SERVER['HTTP_USER_AGENT'] . "<BR>";
echo "Adresse IP client:".$_SERVER['REMOTE_ADDR']."<BR>";
echo "Server: " . $_SERVER['SERVER_NAME'];
?>
</BODY></HTML>
2: Application Layer
68
Résultat
Exemple
le 8/11/2006 à 15:54:29 Client :Mozilla/4.0
(compatible; MSIE 7.0; Windows NT 5.1;
.NET CLR 1.1.4322; InfoPath.1)
Adresse IP client:127.0.0.1
Server: localhost
2: Application Layer
69
Reçu par le client
<HTML> <HEAD>
<TITLE>Exemple très simple</TITLE>
</HEAD>
<BODY>
<H1>Exemple</H1>
le 8/11/2006 à 15:54:29
<P>
Client :Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1;
.NET CLR 1.1.4322; InfoPath.1)<BR>Adresse IP
client:127.0.0.1<BR>Server: localhost
</BODY></HTML>
2: Application Layer
70
Php
 On est ici côté serveur:

les balises <?php> <?> sont interprétées par le
serveur (apache par exemple) et servent à
générer la page html reçu par le client
 Mais surtout php permet
 d'accéder aux variables d'environnement
 d'utiliser de nombreuses fonctionsalités
• sessions, paramètres etc.
 Php sert souvent d'interface pour MySql
serveur simple de bases de données
2: Application Layer
71
Php
 pas de typage ni de déclaration des variables
 $v est remplacé par la valeur de v (et permet aussi
l'affectation)
 echo "$v";
 constantes define("PI, 3.1415);
 types des variables

numériques
• $i=1;
• $v=3.14;

chaînes de caractères (expressions régulières)
• $nom="Hugues";
• ',",{}
2: Application Layer
72
php
 tableaux
 indicés
• $tab[0]="un";
• $tab=array("un","deux","trois");

associatifs
• $m=array("un"=>"one",
"deux"=>"two");
• $m["trois"]="three";

next() prev() key() current
do
{echo "Clé=key($m).Valeur= current($m)"}
while(next($mes));
foreach($m as $cle =>$val)
{echo "Clé=$cle.Valeur=$val";}
2: Application Layer
73
Php
 structures de contrôles
if
 if else
 while
 do while
 for
 foreach

• break, continue
2: Application Layer
74
fonctions
function Nom([$arg1, $arg2, ...])
{
corps
}
passage par valeur (et pas références &)
exemples
function Add($i,$j){
$somme= $i + $j;
return $somme;
}
function Add($i,$j,&$somme){
$somme= $i + $j;
}
2: Application Layer
75
divers
 variables
automatiques (locales)
 statiques (comme en C)
 globales

 classes et objets
2: Application Layer
76
Pour le serveur…
 tableaux associatifs prédéfinis

$_SERVER: environnement serveur
•
•
•
•
•
•
•
•
•
•
REQUEST_METHOD
QUERY_STRING
CONTENT_LENGTH
SERVER_NAME
PATH_INFO
HTTP_USER_AGENT
REMOTE_ADDR
REMOTE_HOST
REMOTE_USER
REMOTE_PASSWORD
2: Application Layer
77
Suite
 Autres tableaux
$_ENV : environnement système
 $_COOKIE
 $_GET
 $_POST
 $_FILES
 $_REQUEST (variables des 4 précédents
 $_SESSION
 $GLOBALS les variables globales du scritp

2: Application Layer
78
Cookies et php
<?php
// Est-ce que le Cookie existe ?
if (isSet($_COOKIE['compteur']))
{
$message = "Vous êtes déjà venu {$_COOKIE['compteur']}
fois "
. "me rendre visite<BR>\n";
// On incrémente le compteur
$valeur = $_COOKIE['compteur'] + 1;
}
else
{
// Il faut créer le cookie avec la valeur 1
$message = "Bonjour, je vous envoie un cookie<BR>\n";
$valeur = 1;
}
// Envoi du cookie
SetCookie ("compteur", $valeur);
?>
2: Application Layer
79
Cookies et php (fin)
<HTML><HEAD>
<TITLE>Les cookies</TITLE>
</HEAD>
<BODY>
<H1>Un compteur d'accès au site avec cookie</H1>
<?php echo $message; ?>
</BODY></HTML>
2: Application Layer
80
En utilisant les sessions
<?php
// La fonction session_start fait tout le travail
session_start();
?>
<HTML><HEAD>
<TITLE>Les cookies</TITLE>
</HEAD>
<BODY>
<H1>Un compteur d'accès au site avec Session</H1>
2: Application Layer
81
Fin
<?php
if (!isSet($_SESSION['cp']))
{
$_SESSION['cp']=1;
echo "C'est la première fois, votre id
est:".session_id()."<BR>";
}
else{
$_SESSION['cp']++;
echo "C'est votre ".$_SESSION['cp']." n-ième
connexion";
if($_SESSION['cp']>10){
echo "on vous a trop vu"."<BR>";
session_destroy();
}
}
?>
</BODY></HTML>
2: Application Layer
82
session
 session_start()
 session_destroy()
 session_id()
 on peut associer des variables à la session par le
tableau associatif $_SESSION
 elle sera accessible à chaque session_start()
jusqu'au session_destroy() pour toute
connexion qui fournit le session_id().
2: Application Layer
83
Chapter 2: Application layer
 2.1 Principles of
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail

SMTP, POP3, IMAP
 2.5 DNS
 2.6 P2P file sharing
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.9 Building a Web
server
2: Application Layer
84
FTP: the file transfer protocol
user
at host
FTP
FTP
user
client
interface
file transfer
local file
system
FTP
server
remote file
system
 transfer file to/from remote host
 client/server model

client: side that initiates transfer (either to/from
remote)
 server: remote host
 ftp: RFC 959
 ftp server: port 21
2: Application Layer
85
FTP: separate control, data connections
TCP control connection
port 21
 FTP client contacts FTP




server at port 21, specifying
TCP as transport protocol
Client obtains authorization
over control connection
Client browses remote
directory by sending
commands over control
connection.
When server receives a
command for a file transfer,
the server opens a TCP data
connection to client
After transferring one file,
server closes connection.
FTP
client
TCP data connection
port 20
FTP
server
 Server opens a second TCP
data connection to transfer
another file.
 Control connection: “out of
band”
 FTP server maintains “state”:
current directory, earlier
authentication
2: Application Layer
86
FTP commands, responses
Sample commands:
Sample return codes
 sent as ASCII text over
 status code and phrase (as
control channel
 USER username
 PASS password
 LIST return list of file in


current directory
 RETR filename retrieves

 STOR filename stores

(gets) file
(puts) file onto remote
host
in HTTP)
331 Username OK,
password required
125 data connection
already open;
transfer starting
425 Can’t open data
connection
452 Error writing
file
2: Application Layer
87