La présentation est en train de télécharger. S'il vous plaît, attendez

La présentation est en train de télécharger. S'il vous plaît, attendez

2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross.

Présentations similaires


Présentation au sujet: "2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross."— Transcription de la présentation:

1 2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross Addison-Wesley, July 2004. Thanks and enjoy! JFK/KWR All material copyright 1996-2005 J.F Kurose and K.W. Ross, All Rights Reserved

2 2: Application Layer2 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP, POP3, IMAP r 2.5 DNS r 2.6 P2P file sharing r 2.7 Socket programming with TCP r 2.8 Socket programming with UDP r 2.9 Building a Web server

3 2: Application Layer3 Chapter 2: Application Layer Our goals: r conceptual, implementation aspects of network application protocols  transport-layer service models  client-server paradigm  peer-to-peer paradigm r learn about protocols by examining popular application-level protocols  HTTP  FTP  SMTP / POP3 / IMAP  DNS r programming network applications  socket API

4 2: Application Layer4 Some network apps r E-mail r Web r Instant messaging r Remote login r P2P file sharing r Multi-user network games r Streaming stored video clips r Internet telephone r Real-time video conference r Massive parallel computing r

5 2: Application Layer5 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 little software written for devices in network core  network core devices do not run user application code  application on end systems allows for rapid app development, propagation application transport network data link physical application transport network data link physical application transport network data link physical

6 2: Application Layer6 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP, POP3, IMAP r 2.5 DNS r 2.6 P2P file sharing r 2.7 Socket programming with TCP r 2.8 Socket programming with UDP r 2.9 Building a Web server

7 2: Application Layer7 Application architectures r Client-server r Peer-to-peer (P2P) r Hybrid of client-server and P2P

8 2: Application Layer8 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

9 2: Application Layer9 Pure P2P architecture r no always-on server r arbitrary end systems directly communicate r peers are intermittently connected and change IP addresses r example: Gnutella Highly scalable But difficult to manage

10 2: Application Layer10 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

11 2: Application Layer11 Processes communicating Process: program running within a host. r within same host, two processes communicate using inter-process communication (defined by OS). r processes in different hosts communicate by exchanging messages Client process: process that initiates communication Server process: process that waits to be contacted r Note: applications with P2P architectures have client processes & server processes

12 2: Application Layer12 Sockets r process sends/receives messages to/from its socket r 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 process TCP with buffers, variables socket host or server process TCP with buffers, variables socket host or server Internet controlled by OS controlled by app developer r API: (1) choice of transport protocol; (2) ability to fix a few parameters (lots more on this later)

13 2: Application Layer13 Addressing processes r For a process to receive messages, it must have an identifier r A host has a unique32- bit IP address r Q: does the IP address of the host on which the process runs suffice for identifying the process? r Answer: No, many processes can be running on same host r Identifier includes both the IP address and port numbers associated with the process on the host. r Example port numbers:  HTTP server: 80  Mail server: 25 r More on this later

14 2: Application Layer14 App-layer protocol defines r Types of messages exchanged, e.g., request & response messages r Syntax of message types: what fields in messages & how fields are delineated r Semantics of the fields, i.e., meaning of information in fields r Rules for when and how processes send & respond to messages Public-domain protocols: r defined in RFCs r allows for interoperability r e.g., HTTP, SMTP Proprietary protocols: r e.g., KaZaA

15 2: Application Layer15 What transport service does an app need? Data loss r some apps (e.g., audio) can tolerate some loss r other apps (e.g., file transfer, telnet) require 100% reliable data transfer Timing r some apps (e.g., Internet telephony, interactive games) require low delay to be “effective” Bandwidth r some apps (e.g., multimedia) require minimum amount of bandwidth to be “effective” r other apps (“elastic apps”) make use of whatever bandwidth they get

16 2: Application Layer16 Transport service requirements of common apps Application file transfer e-mail Web documents real-time audio/video stored audio/video interactive games instant messaging Data loss no loss loss-tolerant no loss Bandwidth elastic audio: 5kbps-1Mbps video:10kbps-5Mbps same as above few kbps up elastic Time Sensitive no yes, 100’s msec yes, few secs yes, 100’s msec yes and no

17 2: Application Layer17 Internet transport protocols services TCP service: r connection-oriented: setup required between client and server processes r reliable transport between sending and receiving process r flow control: sender won’t overwhelm receiver r congestion control: throttle sender when network overloaded r does not provide: timing, minimum bandwidth guarantees UDP service: r unreliable data transfer between sending and receiving process r does not provide: connection setup, reliability, flow control, congestion control, timing, or bandwidth guarantee Q: why bother? Why is there a UDP?

18 2: Application Layer18 Internet apps: application, transport protocols Application e-mail remote terminal access Web file transfer streaming multimedia Internet telephony Application layer protocol SMTP [RFC 2821] Telnet [RFC 854] HTTP [RFC 2616] FTP [RFC 959] proprietary (e.g. RealNetworks) proprietary (e.g., Vonage,Dialpad) Underlying transport protocol TCP TCP or UDP typically UDP

19 2: Application Layer19 Chapter 2: Application layer r 2.1 Principles of network applications  app architectures  app requirements r 2.2 Web and HTTP r 2.4 Electronic Mail  SMTP, POP3, IMAP r 2.5 DNS r 2.6 P2P file sharing r 2.7 Socket programming with TCP r 2.8 Socket programming with UDP r 2.9 Building a Web server

20 2: Application Layer20 Web and HTTP First some jargon r Web page consists of objects r Object can be HTML file, JPEG image, Java applet, audio file,… r Web page consists of base HTML-file which includes several referenced objects r Each object is addressable by a URL r Example URL: www.someschool.edu/someDept/pic.gif host name path name

21 2: Application Layer21 HTTP overview HTTP: hypertext transfer protocol r Web’s application layer protocol r client/server model  client: browser that requests, receives, “displays” Web objects  server: Web server sends objects in response to requests r HTTP 1.0: RFC 1945 r HTTP 1.1: RFC 2068 PC running Explorer Server running Apache Web server Mac running Navigator HTTP request HTTP response

22 2: Application Layer22 HTTP overview (continued) Uses TCP: r client initiates TCP connection (creates socket) to server, port 80 r server accepts TCP connection from client r HTTP messages (application- layer protocol messages) exchanged between browser (HTTP client) and Web server (HTTP server) r TCP connection closed HTTP is “stateless” r server maintains no information about past client requests Protocols that maintain “state” are complex! r past history (state) must be maintained r if server/client crashes, their views of “state” may be inconsistent, must be reconciled aside

23 2: Application Layer23 HTTP connections Nonpersistent HTTP r At most one object is sent over a TCP connection. r HTTP/1.0 uses nonpersistent HTTP Persistent HTTP r Multiple objects can be sent over single TCP connection between client and server. r HTTP/1.1 uses persistent connections in default mode

24 2: Application Layer24 Nonpersistent HTTP Suppose user enters URL www.someSchool.edu/someDepartment/home.index 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 (contains text, references to 10 jpeg images)

25 2: Application Layer25 Nonpersistent HTTP (cont.) 5. HTTP client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects 6. Steps 1-5 repeated for each of 10 jpeg objects 4. HTTP server closes TCP connection. time

26 2: Application Layer26 Response time modeling Definition of RRT: time to send a small packet to travel from client to server and back. Response time: r one RTT to initiate TCP connection r one RTT for HTTP request and first few bytes of HTTP response to return r file transmission time total = 2RTT+transmit time time to transmit file initiate TCP connection RTT request file RTT file received time

27 2: Application Layer27 Persistent HTTP Nonpersistent HTTP issues: r requires 2 RTTs per object r OS overhead for each TCP connection r browsers often open parallel TCP connections to fetch referenced objects Persistent HTTP r server leaves connection open after sending response r subsequent HTTP messages between same client/server sent over open connection Persistent without pipelining: r client issues new request only when previous response has been received r one RTT for each referenced object Persistent with pipelining: r default in HTTP/1.1 r client sends requests as soon as it encounters a referenced object r as little as one RTT for all the referenced objects

28 2: Application Layer28 HTTP request message r two types of HTTP messages: request, response r HTTP request message:  ASCII (human-readable format) GET /somedir/page.html HTTP/1.1 Host: www.someschool.edu User-agent: Mozilla/4.0 Connection: close Accept-language:fr (extra carriage return, line feed) request line (GET, POST, HEAD commands) header lines Carriage return, line feed indicates end of message

29 2: Application Layer29 HTTP request message: general format

30 2: Application Layer30 Uploading form input Post method: r Web page often includes form input r Input is uploaded to server in entity body URL method: r Uses GET method r Input is uploaded in URL field of request line: www.somesite.com/animalsearch?monkeys&banana

31 2: Application Layer31 Method types HTTP/1.0 r GET r POST r HEAD  asks server to leave requested object out of response HTTP/1.1 r GET, POST, HEAD r PUT  uploads file in entity body to path specified in URL field r DELETE  deletes file specified in the URL field

32 2: Application Layer32 Exemple POST POST /path/script.cgi HTTP/1.0 From: frog@jmarshall.com User-Agent: HTTPTool/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 32 home=Cosby&favorite+flavor=flies

33 2: Application Layer33 POST r dans une requête POST il n'y a pas qu'un entête: les données sont dans le corps du message r les données définissent des variables qui seront utilisées par le CGI r l'url requise est normalement un programme r la réponse HTTP est normalement la sortie d'un programme

34 2: Application Layer34 HTTP response message 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... status line (protocol status code status phrase) header lines data, e.g., requested HTML file

35 2: Application Layer35 HTTP response status 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 In first line in server->client response message. A few sample codes:

36 2: Application Layer36 Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: 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 telnet cis.poly.edu 80 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!

37 2: Application Layer37 Méthodes http r GET  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. r HEAD  Cette méthode ne demande que des informations sur la ressource, sans demander la ressource elle-même. r POST  Cette méthode doit être utilisée lorsqu'une requête modifie la ressource. r OPTIONS  Cette méthode permet d'obtenir les options de communication d'une ressource ou du serveur en général. r CONNECT  Cette méthode permet d'utiliser un proxy comme un tunnel de communication. r TRACE  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. r PUT  Cette méthode permet d'ajouter une ressource sur le serveur. r DELETE  Cette méthode permet de supprimer une ressource du serveur.

38 2: Application Layer38 entêtes r Host  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)site Webadresse IP r Referer  Indique l'URI du document qui a donné un lien sur la ressource demandée. Cet en- tête permet aux webmasters d'observer d'où viennent les visiteurs.URIwebmasters r User-Agent  Indique le logiciel utilisé pour se connecter. Il s'agit généralement d'un navigateur Web ou d'un robot d'indexation.navigateur Webrobot d'indexation r Connection  connection persistante ou non r Accept  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. r Accept-Charset  Spécifie les encodages de caractères acceptés. r Accept-Language  Spécifie les langages acceptés.

39 2: Application Layer39 Réponses r Date  Moment auquel le message est généré. r Server  Indique quel modèle de serveur HTTP répond à la requête.serveur HTTP r Content-Length  Indique la taille en octets de la ressource.octets r Content-Type  Indique le type MIME de la ressource.MIME r 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.mémoire cache r Last-Modified  Indique la date de dernière modification de la ressource demandée.

40 2: Application Layer40 Let’s look at HTTP in action r telnet example r Ethereal example

41 2: Application Layer41 CGI r Common Gateway Interface r exécuter du code du côté serveur r Passage de paramètre par la méthode POST ou la méthode GET r Variables d'environnement

42 2: Application Layer42 Exemple r en shell: date.cgi #!/bin/sh tmp=`/bin/date` cat Script Cgi La date courante sur le serveur est $tmp ! r l'URL affichera la date

43 2: Application Layer43 Avec un formulaire: Formulaire simple Répondez aux questions suivantes Prénom : Nom : Age : - de 18 ans 19 à 40 ans 41 à 60 ans + de 60 ans <INPUT TYPE=reset VALUE="Remettre à zéro">

44 2: Application Layer44 Résultat r par la méthode get codage des paramètres: r prenom=Hugues&nom=Fauconnier&age= 41+%E0+60+ans  le navigateur génère l'url: http://www.monsite.com/cgi- bin/treat.pl?prenom=Hugues&nom=Fauconnier&age=41+ %E0+60+ans r Avec la méthode POST http://www.monsite.com/cgi-bin/treat.pl prenom=Hugues&nom=Fauconnier&age=41

45 2: Application Layer45 Traitement en perl r fichier perl fichier perl

46 2: Application Layer46 Paramètres r Les paramètres sont accessibles par l'intermédiaire de la variable d'environnement QUERY_STRING

47 2: Application Layer47 Variables d'environnement r SERVER_SOFTWARE  Le nom et la version du serveur HTTP répondant à la requête. (Format : nom/version) r SERVER_NAME  Le nom d'hôte, alias DNS ou adresse IP du serveur. r GATEWAY_INTERFACE  La révision de la spécification CGI que le serveur utilise. (Format : CGI/révision)

48 2: Application Layer48 Variables… r SERVER_PROTOCOL  Le nom et la révision du protocole dans lequel la requête a été faite (Format : protocole/révision) r SERVER_PORT  Le numéro de port sur lequel la requête a été envoyée. r REQUEST_METHOD  La méthode utilisée pour faire la requête. Pour HTTP, elle contient généralement « GET » ou « POST ». r PATH_INFO  Le chemin supplémentaire du script tel que donné par le client. Par exemple, si le serveur héberge le script « /cgi- bin/monscript.cgi » et que le client demande l'url « http://serveur.org/cgi-bin/monscript.cgi/marecherche », alors PATH_INFO contiendra « marecherche ». r PATH_TRANSLATED  Contient le chemin demandé par le client après que les conversions virtuel → physique aient été faites par le serveur.

49 2: Application Layer49 Variables r SCRIPT_NAME  Le chemin virtuel vers le script étant exécuté. Exemple : « /cgi- bin/script.cgi » r 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&... ». r 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. r REMOTE_ADDR  L'adresse IP du client. r AUTH_TYPE  Le type d'identification utilisé pour protéger le script (s’il est protégé et si le serveur supporte l'identification).

50 2: Application Layer50 Variables r AUTH_TYPE  Le type d'identification utilisé pour protéger le script (s’il est protégé et si le serveur supporte l'identification). r REMOTE_USER  Le nom d'utilisateur du client, si le script est protégé et si le serveur supporte l'identification. r 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. r 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 »). r CONTENT_LENGTH  La longueur du contenu envoyé par le client.

51 2: Application Layer51 Variables r HTTP_ACCEPT Les types de données MIME que le client accepte de recevoir.MIME Exemple : text/*, image/jpeg, image/png, image/*, */* r HTTP_ACCEPT_LANGUAGE Les langages dans lequel le client accepte de recevoir la réponse. Exemple : fr_CA, fr r HTTP_USER_AGENT Le navigateur utilisé par le client.navigateur Exemple : Mozilla/5.0 (compatible; Konqueror/3; Linux)

52 2: Application Layer52 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 e- commerce 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

53 2: Application Layer53 Cookies: keeping “state” (cont.) client server usual http request msg usual http response + Set-cookie: 1678 usual http request msg cookie: 1678 usual http response msg usual http request msg cookie: 1678 usual http response msg cookie- specific action cookie- spectific action server creates ID 1678 for user entry in backend database access Cookie file amazon: 1678 ebay: 8734 Cookie file ebay: 8734 Cookie file amazon: 1678 ebay: 8734 one week later:

54 2: Application Layer54 Cookies (continued) What cookies can bring: r authorization r shopping carts r recommendations r user session state (Web e-mail) Cookies and privacy: r cookies permit sites to learn a lot about you r you may supply name and e-mail to sites r search engines use redirection & cookies to learn yet more r advertising companies obtain info across sites aside

55 2: Application Layer55 Web caches (proxy server) r user sets browser: Web accesses via cache r 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 Goal: satisfy client request without involving origin server client Proxy server client HTTP request HTTP response HTTP request HTTP response origin server origin server

56 2: Application Layer56 More about Web caching r Cache acts as both client and server r Typically cache is installed by ISP (university, company, residential ISP) Why Web caching? r Reduce response time for client request. r Reduce traffic on an institution’s access link. r Internet dense with caches enables “poor” content providers to effectively deliver content (but so does P2P file sharing)

57 2: Application Layer57 Caching example Assumptions r average object size = 100,000 bits r avg. request rate from institution’s browsers to origin servers = 15/sec r delay from institutional router to any origin server and back to router = 2 sec Consequences r utilization on LAN = 15% r utilization on access link = 100% r total delay = Internet delay + access delay + LAN delay = 2 sec + minutes + milliseconds origin servers public Internet institutional network 10 Mbps LAN 1.5 Mbps access link institutional cache

58 2: Application Layer58 Caching example (cont) Possible solution r increase bandwidth of access link to, say, 10 Mbps Consequences r utilization on LAN = 15% r utilization on access link = 15% r Total delay = Internet delay + access delay + LAN delay = 2 sec + msecs + msecs r often a costly upgrade origin servers public Internet institutional network 10 Mbps LAN 10 Mbps access link institutional cache

59 2: Application Layer59 Caching example (cont) Install cache r suppose hit rate is.4 Consequence r 40% requests will be satisfied almost immediately r 60% requests satisfied by origin server r utilization of access link reduced to 60%, resulting in negligible delays (say 10 msec) r total avg delay = Internet delay + access delay + LAN delay =.6*(2.01) secs + milliseconds < 1.4 secs origin servers public Internet institutional network 10 Mbps LAN 1.5 Mbps access link institutional cache

60 2: Application Layer60 Conditional GET r Goal: don’t send object if cache has up-to-date cached version r cache: specify date of cached copy in HTTP request If-modified-since: r server: response contains no object if cached copy is up- to-date: HTTP/1.0 304 Not Modified cache server HTTP request msg If-modified-since: HTTP response HTTP/1.0 304 Not Modified object not modified HTTP request msg If-modified-since: HTTP response HTTP/1.0 200 OK object modified

61 2: Application Layer61 Compléments Javascript r 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.. r Balise : le code...

62 2: Application Layer62 Exemple: bonjourbonjour Très facile function bonjour() { alert ("Bonjour madame, bonjour monsieur"); } Bonjour

63 2: Application Layer63 Un peu plus: minicalculminicalcul HTML> Petit calcul Calcul Un petit exemple de formulaire. Création d'une fenêtre avec JavaScript

64 2: Application Layer64 Suite Argument 1 * Argument 2 <INPUT TYPE='TEXT' SIZE=20 NAME='arg2' onChange='calcul();'> Résultat= <INPUT TYPE='TEXT' SIZE=20 NAME='res' > <INPUT TYPE='RESET' VALUE='Effacer tout' onClick=' if (!confirm("Vraiment vous voulez effacer ?")) exit;'>

65 2: Application Layer65 Fichiers js r ctrl.js calcul ctrl.jscalcul 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 ; }

66 2: Application Layer66 suite et fin r fenetre.js fenetre.js function afficheDoc() { options = "width=300,height=200"; fenetre = window.open('','MU',options); fenetre.document.open(); manuel = " Documentation " + " " + "Il n'y a pas besoin d'aide " + " c'est facile." + " Bonne chance ! "; fenetre.document.write(manuel); fenetre.document.close(); }

67 2: Application Layer67 Compléments: php r php est un langage de script pour les serveurs webs r de nombreuses fonctions permettent de traiter les requêtes http r ici on est du côté du serveur…

68 2: Application Layer68 Exemple simplesimple Exemple très simple Exemple le <?php echo "Client :". $_SERVER['HTTP_USER_AGENT']. " "; echo "Adresse IP client:".$_SERVER['REMOTE_ADDR']." "; echo "Server: ". $_SERVER['SERVER_NAME']; ?>

69 2: Application Layer69 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

70 2: Application Layer70 Reçu par le client Exemple très simple 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

71 2: Application Layer71 Php r On est ici côté serveur:  les balises sont interprétées par le serveur (apache par exemple) et servent à générer la page html reçu par le client r Mais surtout php permet  d'accéder aux variables d'environnement  d'utiliser de nombreuses fonctionsalités sessions, paramètres etc. r Php sert souvent d'interface pour MySql serveur simple de bases de données

72 2: Application Layer72 Php r pas de typage ni de déclaration des variables r $v est remplacé par la valeur de v (et permet aussi l'affectation) r echo "$v"; r constantes define("PI, 3.1415); r types des variables  numériques $i=1; $v=3.14;  chaînes de caractères (expressions régulières) $nom="Hugues"; ',",{}

73 2: Application Layer73 php r 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";}

74 2: Application Layer74 Php r structures de contrôles  if  if else  while  do while  for  foreach break, continue

75 2: Application Layer75 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; }

76 2: Application Layer76 divers r variables  automatiques (locales)  statiques (comme en C)  globales r classes et objets

77 2: Application Layer77 Pour le serveur… r 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

78 2: Application Layer78 Suite r Autres tableaux  $_ENV: environnement système  $_COOKIE  $_GET  $_POST  $_FILES  $_REQUEST (variables des 4 précédents  $_SESSION  $GLOBALS les variables globales du scritp

79 2: Application Layer79 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 \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 \n"; $valeur = 1; } // Envoi du cookie SetCookie ("compteur", $valeur); ?>

80 2: Application Layer80 Cookies et php (fin) Les cookies Un compteur d'accès au site avec cookie

81 2: Application Layer81 En utilisant les sessions <?php // La fonction session_start fait tout le travail session_start(); ?> Les cookies Un compteur d'accès au site avec Session

82 2: Application Layer82 Fin <?php if (!isSet($_SESSION['cp'])) { $_SESSION['cp']=1; echo "C'est la première fois, votre id est:".session_id()." "; } else{ $_SESSION['cp']++; echo "C'est votre ".$_SESSION['cp']." n-ième connexion"; if($_SESSION['cp']>10){ echo "on vous a trop vu"." "; session_destroy(); } ?>

83 2: Application Layer83 session r session_start() r session_destroy() r 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().


Télécharger ppt "2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross."

Présentations similaires


Annonces Google