1: Introduction 1
Applications et protocoles applicatifs
Applications: communiquant, processus distribués
❍S’exécutent dans les hôtes dans l’ « espace utilisateurs »
❍Échangent des messages pour implanter des applis
❍e.g., email, transfert de fichier, le Web Protocoles applicatifs
❍Définissent les messages échangés entre les applis et les actions
❍Certains services sont proposés par les protocoles de couches inférieures
application transport network data link physical
application transport network data link physical application
transport network data link physical
1: Introduction 2
Applications réseaux : le jargon
❒ Unprocessusest un programme qui s’éxécute sur un hôte
❒ Deux processus communiquent dans un même hôte avec des communications
interprocessusdefinis par le système d’exploitation
❒ Deux processus s’éxécutant sur deux hôtes communiquent avec un protocole de couche application
❒
Un
agent utilisateurest une interface entre l’utilisateur et l’application réseau
❍Web:browser
❍E-mail: eudora, outlook
❍streaming audio/video:
real player, media player
1: Introduction 3
Paradigme client-serveur
Les réseaux typiques ont deux
parties : le clientet leserveur application transport network data link physical
application transport network data link physical
Client:
❒ Initie le contact avec le serveur (“parle en premier”)
❒ Typiquement demande un service du serveur
❒ Pour le Web, le client est implanté dans le browser; pour le e-mail dans le lecteur de mail Serveur:
❒ Propose les services demandés par le client
❒ e.g., Le Web serveur envoie les pages Web demandés
request
reply
1: Introduction 4
Protocole applicatif
API: Application
Programming Interface
❒
Définit l’interface entre l’application et la couche transport
❒
socket: API Internet
❍Deux processus communiquent en émettant et recevant des données via les sockets
Q: Comment un
processus « identifie » un processus distant pour communiquer
❍Adresse IP de l’hôte distant
❍“Numéro de port” – permet de différencier les différents processus locaux auxquels le message doit être transmis
Quel est le service de transport nécessaire à une application?
Perte de données
❒ Certaines applis (e.g., audio) peuvent tolérer des pertes
❒ D’autres applis (e.g., ftp, telnet) nécessitent une
fiabilité à 100%
Timing
❒ Certaines applis (e.g., voix sur IP, jeux interactifs) nécessitent un délai faible
Bande passante
❒ Certaines applis (e.g., multimedia) requierent une bande passante minimale
❒ D’autre applis (“applis élastique”) utilisent la bande passante disponible
Besoin en service de transport
Application Transfert de fichier e-mail Web Audio/vidéo Temps réel Audio/vidéo enregistré Jeux interactifs Applis financière
Pertes Sans pertes Sans pertes tolérant tolérant tolérant tolérant Sans pertes
Bande passante élastique élastique élastique audio: 5Kb-1Mb video:10Kb-5Mb similaire Quelques kbps élastique
Sensibilité temp.
Non Non Non oui, 100’s msec oui, quelques secs oui, 100’s msec Oui et non
1: Introduction 7
Services proposés dans Internet
Service TCP:
❒ Orienté connexion:connexion nécessaire entre le client et le serveur
❒ Transport fiable entre le processus émetteur et récepteur
❒ Contrôle de flot: l’émetteur ne submerge pas le récepteur
❒ Contrôle de Congestion : réduit le débit de l’émetteur quand le réseau est congestionné
❒ Ne propose pas:
❍de garanties de délai,
❍de bande passante minimale
Service UDP:
❒
Transfert de données non fiable
❒
Ne propose pas
❍de connexion,
❍de fiabilité,
❍de contrôle de flot,
❍de contrôle de congestion,
❍de garantie temporelle,
❍de bande passante
1: Introduction 8
Applis Internet: protocoles applicatifs et protocoles de transport
Application e-mail Accès distant Web Transfert de fichier streaming multimedia Fichier distant Voix sur IP
Protocole applicatif smtp [RFC 821]
telnet [RFC 854]
http [RFC 2068]
ftp [RFC 959]
proprietaire (e.g. RealNetworks) NSF
proprietaire (e.g., Vocaltec)
Protocole de transport TCP TCP TCP TCP TCP or UDP TCP or UDP typically UDP
1: Introduction 9
Le Web: jargon
❒
Page Web:
❍Contient des “objects”
❍Adressée par une URL
❒
La plupart des pages Web pages contiennent :
❍Page HTML de base
❍Objets référencés
❒
L’URL a deux composants:
❍nom d’hôte
❍chemin d’accès
❒
L’Agent Utilisateur pour le Web est le browser:
❍MS Internet Explorer
❍Netscape Communicator
❒
Le serveur Web:
❍Apache (domaine public)
❍MS Internet Information Server
www.someSchool.edu/someDept/pic.gif
1: Introduction 10
Le Web: le protocole HTTP
HTTP: HyperText Transfer Protocol
❒ Couche applicative Web
❒ Modèle client/serveur
❍client:le browser, qui demande, reçoit, affiche les objets Web
❍serveur:le serveur Web, qui envoie les réponses aux requêtes
❒ http1.0: RFC 1945
❒ http1.1: RFC 2068
PC exécutant Explorer
Server exécutant
Apache server
Mac exécutant Netscape
http request
http request http response
http response
1: Introduction 11
Le protocole HTTP
HTTP:
service de transport TCP
❒ Le client initie une connexion TCP (crée une socket) avec le serveur, port 80
❒ Le serveur accepte la connexionTCP du client
❒ Les messages HTTP (protocole applicatif) sont échangés entre le browser (client HTTP) et le serveur Web
❒ La connexion TCP est close
HTTP est « sans état »
❒ Le serveur ne maintient aucune information au sujet des requêtes précédentes des clients
Les protocoles gardant un
“état” sont complexes !
❒ L’histoire passée doit être gardée
❒ Si le serveur ou le client se crashe les états peuvent être incohérents
1: Introduction 12
Exemple HTTP
Si un utilisateur entre l’URL :
www.someSchool.edu/someDepartment/home.index 1a.Le client HTTP initie une
connexion TCP au serveur HTTP sur le site
www.someSchool.edu. Le port 80 est choisi par défaut 2.Le client HTTP envoie les
requêtes HTTP (contenant des URLs) par les sockets TCP
1b.Le serveur HTTP du site www.someSchool.eduattend une connexion TCP sur le port 80. Il “accepte” la connexion, et l’annonce au client 3.Le serveur HTTP reçoit le
message de requête, génère le message de réponsecontenant l’objet requis
(someDepartment/home.index), et l’envoie sur une socket
time
1: Introduction 13
Exemple HTTP (suite)
5. Le client HTTP reçoit la réponse contenant le fichier HTML file et l’affiche.
En décodant le fichier, le browser trouve les URLs référencées
6.Les étapes 1-5 sont répétées pour chaque URL référencée
4.Le serveur HTTP ferme la connexion TCP
time
1: Introduction 14
Connexions Persistantes et Non-persistantes
Non-persistante
❒ HTTP/1.0
❒ Le serveur interprète les requêtes, répond et ferme la connexion TCP
❒ 2 RTTs sont nécessaires pour lire chaque objet
❒ Chaque transfert doit supporter le slow-start
❒ Exemple : page contenant :
❍ 1 fichier HTML
❍10 images JPEG
Persistante
❒ Par défaut dans HTTP/1.1
❒ Une seule connexion TCP est ouverte vers le serveur
❒ Le client envoie la requête de tous les objets requis dès qu’ils sont réferencés dans le HTML
❒ Moins de RTTs et moins de slow start.
❒ Deux versions : avec/sans pipeline
Mais la plupart des navigateurs
de version 1.0 utilisent des connexions parallèles
1: Introduction 15
Format de message http : requête
❒
Deux types de messages http : requête , réponse
❒
message de requête http :
❍ASCII
GET /somedir/page.html HTTP/1.0 Host: www.someschool.edu Connection: close User-agent: Mozilla/4.0
Accept: text/html, image/gif,image/jpeg Accept-language:fr
Ligne de requête (commandes GET, POST, HEAD)
Lignes d’entête Le retour chariot
indique la fin du message
1: Introduction 16
Format de message http : requête
Format de message http : réponse
HTTP/1.0 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 ...
Ligne d'état (protocole, code d'état, message d'état)
Lignes d’entête
données, e.g., Le fichier
html
Format de message http : réponse
Status Line
1: Introduction 19
Code de réponse HTTP
200 OK
❍La requête a réussi et l’objet demandé est à la suite 301 Moved Permanently
❍L’objet demandé a changé définitivement de place, son nouvel emplacement est donné dans la suite du message 400 Bad Request
❍La requête est erronée 404 Not Found
❍Le document demandé n’est pas disponible sur le serveur 505 HTTP Version Not Supported
Dans la première ligne de la réponse serveur->client.
1: Introduction 20
Essayer le serveur http
1. Telnet à votre serveur web favori
Ouvre une connexion TCP vers le port 80 de www.eurecom.fr.
telnet www.eurecom.fr 80
2. Taper une requête HTTP
GET /~ross/index.html HTTP/1.0
1: Introduction 21
Interaction entre le client et le serveur Authentification
❒
De nombreux sites demandent un identifiant et un mot de passe
❒
HTTP fournit des codes et des entêtes d'état pour permettre l'auhentification
❒
Client : requête
❒
Serveur : 401 Authorization Required
❒
Client : Authorization : …
❍
user name
❍
password
1: Introduction 22
Interaction entre le client et le serveur Cookies
❒ RFC 2109
❒ Le serveur envoie un
“cookie” vers le client dans la reponse
Set-cookie: 1678453
❒ Le client présente le cookie dans les requêtes suivantes
cookie: 1678453
❒ Le serveur vérifie le cookie avec ces informations enregistrées
❍authentification
❍Rappel des préférences utilisateur
client server
requête http Réponse http + Set-cookie: #
requête http+
cookie: # Réponse http
Opération Spécifique au cookie
1: Introduction 23
Utilité des cookies
❒
Serveur nécessitant une authentification, sans demander systématiquement un identifiant et un mot de passe
❒
Trace des préférences de l'utilisateur, par exemple pour faire de la publicité ciblée
❒
Garder une trace des achats de l'utilisateur lors d'achats en ligne
❒
…
❒
Problème : utilisateurs nomades accédant à un même site depuis différentes machines
1: Introduction 24
GET conditionnel
❒ Objectif :ne pas envoyer un objet que le client a déjà dans son cache
❒ Problème : les objets contenus dans le cache peuvent être obsolètes
❒ client: spécifie la date de la copie cachée dans la requête http
If-modified-since:
<date>
❒ serveur: la réponse est vide si la copie cachée est à jour HTTP/1.0 304 Not Modified
client serveur
Requête http If-modified-since:
<date>
Réponse http HTTP/1.0 304 Not Modified
objet modifiénon
Requête http If-modified-since:
<date>
Réponse http HTTP/1.1 200 OK
…
<data>
objet modifié
1: Introduction 25
Cache Web / proxy server
❒ Configuration du browser pour qu'il pointe vers le cache
❒ Le client envoie toutes ses requêtes HTTP vers le cache Web
❍Si l’objet est dans le cache, on le renvoie
❍Sinon on demande au serveur initial et on répond ensuite à la requête
Objectif :
satisfaire la requête du client sans utiliser le serveur initialclient
Proxy server
client http request http request http response
http response
http request http response http request http response
origin server origin server
1: Introduction 26
Intérêt du cache Web
Hypothèse : le cache est proche du client
❒
Réduction du temps de réponse
❒
Réduction du débit vers les serveurs distants
origin servers public
Internet
institutional
network 10 Mbps LAN
1.5 Mbps access link
institutional cache
1: Introduction 27
DNS: Domain Name System
Gens: plusieurs identifiants
❍NSS, name, # Passeport
Hôtes, routeurs:
❍Adresse IP (32 bits)
❍“nom” : www.yahoo.com, gaia.cs.umass.edu
Q: Comment relier les adresses et les noms ?
Domain Name System:
❒
Base de données distribuées implémentée dans une hiérarchie de serveurs de noms
❒
Protocole applicatif
❍hôtes, routeurs, serveurs de noms qui communiquent pour effectuer la traduction
❍DNS utilisé par d'autres protocoles applicatifs
❍La complexité est repoussée à la bordure du réseau
1: Introduction 28
Autres services fournis par le DNS
❒
Host aliasing
❒
Mail server aliasing
❒
Répartition de la charge
❒
RFC 1034 et 1035
❒
Pour l'utilisateur, DNS = boîte noire
DNS name servers
❒ Aucun serveur n’a toutes les relations nom-vers-@IP Serveurs de noms locaux:
❍Chaque ISP ou entreprise a son propre (default) name server
❍Les requêtes DNS vont en premier au serveur de nom local Serveurs de noms racines:
❍Il existe une douzaine de root name servers dans l'Internet Serveurs de noms "authoritative":
❍Chaque hôte est enregistré auprès d'un serveur
"authoritative", qui stocke son adresse IP et son nom
❍Peut effectuer la traduction nom/adresse pour cet hôte
Pourquoi pas de DNS centralisé?
❒
Tolérance aux pannes (Si le DNS crashe, tout l'Internet aussi !)
❒
Volume de trafic
❒
Délais de réponse
❒
Maintenance (Mises à jour)
Ne passe pas à l’échelle !
DNS: Root name servers
❒ contacted by local name server that can not resolve name
❒ root name server:
❍contacts authoritative name server if name mapping not known
❍gets mapping
❍returns mapping to local name server
❒ ~ dozen root name servers worldwide
1: Introduction 31
Simple DNS example
host surf.eurecom.fr wants IP address of gaia.cs.umass.edu 1.Contacts its local DNS
server,dns.eurecom.fr 2.dns.eurecom.frcontacts
root name server, if necessary
3.root name server contacts authoritative name server, dns.umass.edu,if
necessary requesting host
surf.eurecom.fr gaia.cs.umass.edu root name server
authorititive name server dns.umass.edu local name server
dns.eurecom.fr 1
2 3 4
5
6
1: Introduction 32
DNS example
Root name server:
❒ may not know authoritative name server
❒ may know intermediate name server:who to contact to find authoritative name server
requesting host surf.eurecom.fr
gaia.cs.umass.edu root name server
local name server dns.eurecom.fr
1
2 3
4 5
6
authoritative name server dns.cs.umass.edu intermediate name server
dns.umass.edu 7
8
1: Introduction 33
DNS: iterated queries
recursive query:
❒ puts burden of name resolution on contacted name server
❒ heavy load?
iterated query:
❒ contacted server replies with name of server to contact
❒ “I don’t know this name, but ask this server”
requesting host surf.eurecom.fr
gaia.cs.umass.edu root name server
local name server dns.eurecom.fr
1 2 3
4
5 6
authoritative name server dns.cs.umass.edu intermediate name server
dns.umass.edu 7
8
iterated query
1: Introduction 34
DNS caching
❒
once (any) name server learns mapping, it caches mapping
❍
cache entries timeout (disappear) after some time
❒
update/notify mechanisms under design by IETF
❍RFC 2136
❍http://www.ietf.org/html.charters/dnsind-charter.html
1: Introduction 35
DNS records
DNS:
distributed DB storing Resource Records (RR)
❒
Type=NS
❍nameis domain (e.g.
foo.com)
❍valueis IP address of authoritative name server for this domain
RR format:
(name, value, type, TTL)❒
Type=A
❍nameis hostname
❍valueis IP address
❒
Type=CNAME
❍nameis an alias name for some “cannonical”
(the real) name
❍valueis cannonical name
❒
Type=MX
❍valueis hostname of mailserver associated with name
1: Introduction 36
DNS protocol, messages
DNS protocol :queryand replymessages, both with same message format
msg header
❒ identification:16 bit # for query, repy to query uses same #
❒ flags:
❍query or reply
❍recursion desired
❍recursion available
❍reply is authoritative
1: Introduction 37
DNS protocol, messages
Name, type fields for a query RRs in response to query records for authoritative servers additional “helpful”
info that may be used
1: Introduction 38
FTP: the file transfer protocol
❒ 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
file transfer FTP server userFTP
interface FTP client
local file
system remote file
system user
at host
1: Introduction 39
ftp: separate control, data connections
❒ ftp client contacts ftp server at port 21, specifying TCP as transport protocol
❒ two parallel TCP connections opened:
❍control:exchange commands, responses between client, server.
“out of band control”
❍data:file data to/from server
❒ ftp server maintains “state”:
current directory, earlier authentication
clientFTP FTP
server TCP control connection
port 21
TCP data connection port 20
1: Introduction 40
ftp commands, responses
Sample commands:
❒ sent as ASCII text over control channel
❒ USER username
❒ PASS password
❒ LISTreturn list of file in current directory
❒ RETR filenameretrieves (gets) file
❒ STOR filenamestores (puts) file onto remote host
Sample return codes
❒ status code and phrase (as in http)
❒ 331 Username OK, password required
❒ 125 data connection already open;
transfer starting
❒ 425 Can’t open data connection
❒ 452 Error writing file
Electronic Mail
Three major components:
❒ user agents
❒ mail servers
❒ simple mail transfer protocol: smtp User Agent
❒ a.k.a. “mail reader”
❒ composing, editing, reading mail messages
❒ e.g., Eudora, Outlook, elm, Netscape Messenger
❒ outgoing, incoming messages stored on server
user mailbox outgoing message queue
mail server
agentuser
agentuser
agentuser mail
server agentuser agentuser servermail
user agent
SMTP SMTP SMTP
Electronic Mail: mail servers
Mail Servers
❒ mailboxcontains incoming messages (yet to be read) for user
❒ messagequeue of outgoing (to be sent) mail messages
❒ smtp protocolbetween mail servers to send email messages
❍client: sending mail server
❍“server”: receiving mail server
servermail user agent
user agent
agentuser servermail
user agent user agent mail server
agentuser
SMTP
SMTP
SMTP
1: Introduction 43
Electronic Mail: smtp [RFC 821]
❒ uses tcp to reliably transfer email msg from client to server, port 25
❒ direct transfer: sending server to receiving server
❒ three phases of transfer
❍handshaking (greeting)
❍transfer of messages
❍closure
❒ command/response interaction
❍commands:ASCII text
❍response:status code and phrase
❒
messages must be in 7-bit ASCII
1: Introduction 44
Sample smtp interaction
S: 220 hamburger.edu C: HELO crepes.fr
S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <alice@crepes.fr>
S: 250 alice@crepes.fr... Sender ok C: RCPT TO: <bob@hamburger.edu>
S: 250 bob@hamburger.edu ... Recipient ok C: DATA
S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery C: QUIT
S: 221 hamburger.edu closing connection
1: Introduction 45
try smtp interaction for yourself:
❒ telnet servername 25
❒
see 220 reply from server
❒
enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands
above lets you send email without using email client (reader)
1: Introduction 46
smtp: final words
❒ smtp uses persistent connections
❒ smtp requires that message (header & body) be in 7-bit ascii
❒ certain character strings are not permitted in message (e.g., CRLF.CRLF).
Thus message has to be encoded (usually into either base-64 or quoted printable)
❒ smtp server uses CRLF.CRLFto determine end of message
Comparison with http
❒ http: pull
❒ email: push
❒ both have ASCII command/response interaction, status codes
❒ http: each object is encapsulated in its own response message
❒ smtp: multiple objects message sent in a multipart message
1: Introduction 47
Mail message format
smtp: protocol for exchanging email msgs
RFC 822: standard for text message format:
❒ header lines, e.g.,
❍To:
❍From:
❍Subject:
differentfrom smtp commands!
❒ body
❍the “message”, ASCII characters only
header
body
blank line
1: Introduction 48
Message format: multimedia extensions
❒ MIME: multimedia mail extension, RFC 2045, 2056
❒ additional lines in msg header declare MIME content type
From: alice@crepes.fr To: bob@hamburger.edu
Subject: Picture of yummy crepe.
MIME-Version: 1.0
Content-Transfer-Encoding: base64 Content-Type: image/jpeg base64 encoded data ...
...
...base64 encoded data multimedia data
type, subtype, parameter declaration method used to encode data MIME version
encoded data
1: Introduction 49
MIME types
Content-Type: type/subtype; parameters
Text
❒ example subtypes: plain, html
Image
❒ example subtypes: jpeg, gif
Audio
❒ exampe subtypes: basic (8-bit mu-law encoded), 32kadpcm (32 kbps coding)
Video
❒ example subtypes: mpeg, quicktime
Application
❒ other data that must be processed by reader before “viewable”
❒ example subtypes:
msword, octet-stream
1: Introduction 50
Multipart Type
From: alice@crepes.fr To: bob@hamburger.edu
Subject: Picture of yummy crepe.
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=98766789 --98766789
Content-Transfer-Encoding: quoted-printable Content-Type: text/plain
Dear Bob,
Please find a picture of a crepe.
--98766789
Content-Transfer-Encoding: base64 Content-Type: image/jpeg base64 encoded data ...
...
...base64 encoded data --98766789--
1: Introduction 51
Mail access protocols
❒ SMTP: delivery/storage to receiver’s server
❒ Mail access protocol: retrieval from server
❍POP: Post Office Protocol [RFC 1939]
• authorization (agent <-->server) and download
❍IMAP: Internet Mail Access Protocol [RFC 1730]
• more features (more complex)
• manipulation of stored msgs on server
❍HTTP: Hotmail , Yahoo! Mail, etc.
agentuser
sender’s mail server agentuser
SMTP SMTP POP3 or
IMAP
receiver’s mail server
1: Introduction 52
POP3 protocol
authorization phase
❒ client commands:
❍user:declare username
❍pass:password
❒ server responses
❍+OK
❍-ERR
transaction phase,
client:❒ list:list message numbers
❒ retr:retrieve message by number
❒ dele:delete
❒ quit
C: list S: 1 498 S: 2 912 S: . C: retr 1
S: <message 1 contents>
S: . C: dele 1 C: retr 2
S: <message 1 contents>
S: . C: dele 2 C: quit
S: +OK POP3 server signing off S: +OK POP3 server ready C: user alice
S: +OK C: pass hungry
S: +OKuser successfully logged on
Socket programming
Socket API
❒ introduced in BSD4.1 UNIX, 1981
❒ explicitly created, used, released by apps
❒ client/server paradigm
❒ two types of transport service via socket API:
❍unreliable datagram
❍reliable, byte stream- oriented
a host-local, application- created/owned, OS-controlledinterface
(a “door”) into which application process can
both send and receivemessages to/from
another (remote or local) application process
socket
Goal: learn how to build client/server application that communicate using sockets
Socket-programming using TCP
Socket: a door between application process and end- end-transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one process to another
process TCP with buffers, variables socket controlled by
application developer controlled by operating system
host or server
process TCP with buffers, variables socket
controlled by application developer controlled by operating system host or
server internet
1: Introduction 55
Socket programming with TCP
Client must contact server
❒ server process must first be running
❒ server must have created socket (door) that welcomes client’s contact Client contacts server by:
❒ creating client-local TCP socket
❒ specifying IP address, port number of server process
❒ When client creates socket:
client TCP establishes connection to server TCP
❒ When contacted by client, server TCP creates new socketfor server process to communicate with client
❍allows server to talk with multiple clients
TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server application viewpoint
1: Introduction 56
Socket programming with TCP
Example client-server app:
❒ client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream)
❒ server reads line from socket
❒ server converts line to uppercase, sends back to client
❒ client reads, prints modified line from socket
(inFromServerstream)
Input stream: sequence of bytes into process Output stream: sequence of
bytes out of process
client socket inFromUser outToServer iinFromServer
1: Introduction 57
Client/server socket interaction: TCP
wait for incoming connection request connectionSocket = welcomeSocket.accept() create socket, port=x, for incoming request:
welcomeSocket = ServerSocket()
create socket, connect to hostid, port=x clientSocket =
Socket()
close connectionSocket
read reply from clientSocket close clientSocket
Server
(running on hostid)Client
send request using clientSocket read request from
connectionSocket write reply to connectionSocket
connection setupTCP
1: Introduction 58
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
Create input stream Create client socket, connect to server Create output stream attached to socket
1: Introduction 59
Example: Java client (TCP), cont.
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
} } Create input stream attached to socket
Send line to server Read line from server
1: Introduction 60
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket
1: Introduction 61
Example: Java server (TCP), cont
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
} } } Read in line from socket Create output stream, attached to socket
Write out line to socket
End of while loop, loop back and wait for another client connection
1: Introduction 62
Socket programming with UDP
UDP: no “connection” between client and server
❒ no handshaking
❒ sender explicitly attaches IP address and port of destination
❒ server must extract IP address, port of sender from received datagram UDP: transmitted data may be
received out of order, or lost
application viewpoint
UDP provides unreliable transfer of groups of bytes (“datagrams”)
between client and server
1: Introduction 63
Client/server socket interaction: UDP
close clientSocket
Server
(running on hostid)read reply from clientSocket create socket, clientSocket = DatagramSocket()
Client
Create, address (hostid, port=x, send datagram request usingclientSocket create socket,
port=x, for incoming request:
serverSocket = DatagramSocket()
read request from serverSocket write reply to serverSocket specifying client host address, port umber
1: Introduction 64
Example: Java client (UDP)
import java.io.*;
import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception {
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Create input stream Create client socket Translate hostname to IP address using DNS
Example: Java client (UDP), cont.
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
} } Create datagram with data-to-send, length, IP addr, port Send datagram
to server
Read datagram from server
Example: Java server (UDP)
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception {
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true) {
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
Create datagram socket at port 9876
Create space for received datagram Receive datagram
1: Introduction 67
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
} } } Get IP addr
port #, of sender
Write out datagram to socket
End of while loop, loop back and wait for another datagram Create datagram
to send to client