3rdedition Chapter2
3rdedition Chapter2
Application Layer
2: Application Layer 2
Chapter 2: Application Layer
Our goals: learn about
conceptual, protocols by
implementation examining popular
aspects of network application-level
application protocols
protocols HTTP
transport-layer
FTP
SMTP / POP3 / IMAP
service models DNS
client-server
programming
paradigm
network applications
peer-to-peer socket API
paradigm
2: Application Layer 3
Some network apps
E-mail Internet telephone
Web Real-time video
Instant messaging conference
Remote login Massive parallel
P2P file sharing computing
Multi-user network
games
Streaming stored
video clips
2: Application Layer 4
Creating a network app
Write programs that applicatio
n
run on different end transport
network
systems and data link
physical
communicate over a
network.
e.g., Web: Web server
software communicates
with browser software
little software written for
devices in network core applicatio
applicatio
n
network core devices do n
transport
transport
network
not run user application network
data link
data link
physical
code physical
application on end
systems allows for rapid
app development,
propagation 2: Application Layer 5
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
2.2 Web and HTTP programming with TCP
2.3 FTP 2.8 Socket
2.4 Electronic Mail programming with
SMTP, POP3, IMAP UDP
2.5 DNS 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
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 Client process: process
running within a host. that initiates
within same host, two communication
processes Server process:
communicate using process that waits to
inter-process be contacted
communication
(defined by OS). Note: applications
processes in different with P2P architectures
hosts communicate by have client processes
exchanging messages & server processes
2: Application Layer 11
Sockets
host or host or
process sends/receives
server server
messages to/from its
socket controlled by
app developer
socket analogous to door process process
sending process shoves socket socket
message out door TCP with TCP with
sending process relies on buffers, Internet buffers,
transport infrastructure on variables variables
other side of door which
brings message to socket controlled
at receiving process 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 Identifier includes
receive messages, it both the IP address
must have an identifier and port numbers
A host has a unique32- associated with the
bit IP address process on the host.
Q: does the IP address Example port
of the host on which numbers:
the process runs HTTP server: 80
suffice for identifying Mail server: 25
the process?
More on this later
Answer: No, many
processes can be
running on same host
2: Application Layer 13
App-layer protocol defines
Types of messages Public-domain
exchanged, e.g., request protocols:
& response messages defined in RFCs
Syntax of message
allows for
types: what fields in
messages & how fields interoperability
are delineated e.g., HTTP, SMTP
Semantics of the fields, Proprietary protocols:
i.e., meaning of e.g., KaZaA
information in fields
Rules for when and how
processes send &
respond to messages
2: Application Layer 14
What transport service does an app
need?
Data loss Bandwidth
some apps (e.g., audio) some apps (e.g.,
can tolerate some loss multimedia) require
other apps (e.g., file minimum amount of
transfer, telnet) require bandwidth to be
100% reliable data “effective”
transfer other apps (“elastic
Timing apps”) make use of
some apps (e.g., whatever bandwidth
Internet telephony, they get
interactive games)
require low delay to
be “effective”
2: Application Layer 15
Transport service requirements of common
apps
2: Application Layer 16
Internet transport protocols services
Application Underlying
Application layer protocol transport protocol
2: Application Layer 18
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
app architectures programming with TCP
app requirements 2.8 Socket
2.2 Web and HTTP
programming with
2.4 Electronic Mail UDP
SMTP, POP3, IMAP 2.9 Building a Web
2.5 DNS 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:
[Link]/someDept/[Link]
2: Application Layer 20
HTTP overview
HTTP: hypertext
transfer protocol HT
TP
requ
Web’s application layer H
PC running TT est
Pr
protocol Explorer esp
ons
client/server model e
client: browser that
e st
requests, receives, u
req se Server
T P n
“displays” Web objects HT spo running
r e
server: Web server T TP Apache Web
H server
sends objects in
response to requests
HTTP 1.0: RFC 1945 Mac running
Navigator
HTTP 1.1: RFC 2068
2: Application Layer 21
HTTP overview (continued)
Uses TCP: HTTP is “stateless”
client initiates TCP server maintains no
connection (creates information about
socket) to server, port 80 past client requests
server accepts TCP
connection from client aside
Protocols that maintain
HTTP messages “state” are complex!
(application-layer protocol past history (state) must
messages) exchanged be maintained
between browser (HTTP if server/client crashes,
client) and Web server
their views of “state”
(HTTP server)
may be inconsistent,
TCP connection closed
must be reconciled
2: Application Layer 22
HTTP connections
Nonpersistent HTTP Persistent HTTP
At most one object is Multiple objects can
sent over a TCP be sent over single
connection. TCP connection
HTTP/1.0 uses between client and
nonpersistent HTTP server.
HTTP/1.1 uses
persistent
connections in
default mode
2: Application Layer 23
Nonpersistent HTTP
(contains text,
Suppose user enters URL [Link]/someDepartment/[Link]
references to 10
jpeg images)
2: Application Layer 25
Response time modeling
Definition of RRT: time to
send a small packet to
travel from client to
server and back. initiate TCP
Response time: connection
RTT
one RTT to initiate TCP
request
connection file
one RTT for HTTP request time to
RTT
transmit
and first few bytes of file
file
HTTP response to return received
file transmission time
total = 2RTT+transmit time time time
2: Application Layer 26
Persistent HTTP
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, GET /somedir/[Link] HTTP/1.1
HEAD commands) Host: [Link]
User-agent: Mozilla/4.0
header Connection: close
lines Accept-language:fr
Carriage return,
line feed (extra carriage return, line feed)
indicates end
of message
2: Application Layer 28
HTTP request message: general
format
2: Application Layer 29
Uploading form input
Post method:
Web page often
includes form input URL method:
Input is uploaded to Uses GET method
server in entity body Input is uploaded in
URL field of request
line:
[Link]/animalsearch?monkeys&banana
2: Application Layer 30
Method types
HTTP/1.0 HTTP/1.1
GET GET, POST, HEAD
POST PUT
HEAD uploads file in entity
body to path specified
asks server to leave
in URL field
requested object out
of response DELETE
deletes file specified
in the URL field
2: Application Layer 31
HTTP response message
status line
(protocol
status code HTTP/1.1 200 OK
status phrase) Connection close
Date: Thu, 06 Aug 1998 12:00:15 GMT
header Server: Apache/1.3.0 (Unix)
lines Last-Modified: Mon, 22 Jun 1998 …...
Content-Length: 6821
Content-Type: text/html
2: Application Layer 32
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 33
Trying out HTTP (client side) for yourself
2: Application Layer 34
Let’s look at HTTP in action
telnet example
Ethereal example
2: Application Layer 35
User-server state: cookies
Many major Web sites Example:
use cookies Susan access Internet
Four components: always from same PC
1) cookie header line of
She visits a specific e-
HTTP response commerce site for
message first time
2) cookie header line in
When initial HTTP
HTTP request message requests arrives at
3) cookie file kept on site, site creates a
user’s host, managed unique ID and creates
by user’s browser an entry in backend
database for ID
4) back-end database at
Web site
2: Application Layer 36
Cookies: keeping “state” (cont.)
client server
Cookie file usual http request n e
server da try i
msg ta b n b
usual http response creates ID as ac
e
ebay: 8734 ke
+ 1678 for user nd
Set-cookie: 1678
Cookie file
usual http request
amazon: 1678 msg cookie- s s
ebay: 8734 specific acce
cookie: 1678
usual http response action
msg
s
one week later:
s
ce
ac
Cookie file usual http request
msg
cookie-
amazon: 1678
cookie: 1678 spectific
ebay: 8734 usual http response action
msg
2: Application Layer 37
Cookies (continued)
aside
What cookies can Cookies and privacy:
bring: cookies permit sites to
authorization learn a lot about you
you may supply name
shopping carts
and e-mail to sites
recommendations
search engines use
user session state
redirection & cookies
(Web e-mail) to learn yet more
advertising
companies obtain info
across sites
2: Application Layer 38
Web caches (proxy server)
Goal: satisfy client request without involving origin
server
user sets browser: Web origin
accesses via cache server
browser sends all HTTP Proxy
HT st
TP
requests to cache req server reque
H ues se
client TTP t T TP on
object in cache: cache re s H
esp
pon r
returns object se H TTP
e st
else cache requests u
req se
object from origin P n
HT
T
spo
e
server, then returns
T Pr
object to client HT
client
origin
server
2: Application Layer 39
More about Web caching
Cache acts as both client Why Web caching?
and server Reduce response time for
Typically cache is
client request.
installed by ISP Reduce traffic on an
(university, company, institution’s access link.
residential ISP)
Internet dense with
caches enables “poor”
content providers to
effectively deliver
content (but so does P2P
file sharing)
2: Application Layer 40
Caching example
origin
Assumptions
servers
average object size = 100,000
bits public
avg. request rate from Internet
2: Application Layer 41
Caching example (cont)
origin
Possible solution
servers
increase bandwidth of
public
access link to, say, 10 Mbps
Internet
Consequences
utilization on LAN = 15%
utilization on access link =
15% 10 Mbps
access link
Total delay = Internet delay +
access delay + LAN delay institutional
network
= 2 sec + msecs + msecs 10 Mbps LAN
often a costly upgrade
institutional
cache
2: Application Layer 42
Caching example (cont)
origin
Install cache servers
suppose hit rate is .4 public
Consequence Internet
40% requests will be
satisfied almost
immediately
60% requests satisfied by 1.5 Mbps
origin server access link
utilization of access link institutional
reduced to 60%, resulting network
10 Mbps LAN
in negligible delays (say
10 msec)
total avg delay =
Internet delay + access
delay + LAN delay institutional
= .6*(2.01) secs + cache
milliseconds < 1.4 secs
2: Application Layer 43
Conditional GET
2: Application Layer 45
FTP: the file transfer protocol
2: Application Layer 46
FTP: separate control, data
connections
TCP control
FTP client contacts FTP connection
server at port 21, specifying port 21
TCP as transport protocol
TCP data connection
Client obtains authorization FTP port 20 FTP
over control connection client server
Client browses remote
directory by sending Server opens a second TCP
commands over control data connection to transfer
connection. another file.
When server receives a Control connection: “out of
command for a file transfer, band”
the server opens a TCP data FTP server maintains
connection to client
“state”: current directory,
After transferring one file,
earlier authentication
server closes connection.
2: Application Layer 47
FTP commands, responses
2: Application Layer 48
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
2.2 Web and HTTP programming with TCP
2.3 FTP 2.8 Socket
2.4 Electronic Mail programming with
SMTP, POP3, IMAP UDP
2.5 DNS 2.9 Building a Web
server
2: Application Layer 49
Electronic Mail outgoing
message queue
user mailbox
user
Three major components: agent
user agents mail
user
mail servers server
agent
simple mail transfer
SMTP mail
protocol: SMTP
server user
2: Application Layer 50
Electronic Mail: mail servers
user
Mail Servers agent
mailbox contains
mail
user
incoming messages for server
agent
user
message queue of
SMTP mail
server user
outgoing (to be sent) mail
messages SMTP agent
2: Application Layer 51
Electronic Mail: SMTP [RFC 2821]
uses TCP to reliably transfer email message 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
2: Application Layer 52
Scenario: Alice sends message to
Bob
1) Alice uses UA to compose 4) SMTP client sends Alice’s
message and “to” message over the TCP
bob@[Link] connection
2) Alice’s UA sends 5) Bob’s mail server places
message to her mail the message in Bob’s
server; message placed mailbox
in message queue 6) Bob invokes his user
3) Client side of SMTP opens agent to read message
TCP connection with
Bob’s mail server
1 mail
mail
server user
user server
2 agent
agent 3 6
4 5
2: Application Layer 53
Sample SMTP interaction
S: 220 [Link]
C: HELO [Link]
S: 250 Hello [Link], pleased to meet you
C: MAIL FROM: <alice@[Link]>
S: 250 alice@[Link]... Sender ok
C: RCPT TO: <bob@[Link]>
S: 250 bob@[Link] ... 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 [Link] closing connection
2: Application Layer 54
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)
2: Application Layer 55
SMTP: final words
SMTP uses persistent Comparison with HTTP:
connections
HTTP: pull
SMTP requires message
SMTP: push
(header & body) to be in
7-bit ASCII both have ASCII
SMTP server uses
command/response
[Link] to determine interaction, status codes
end of message
HTTP: each object
encapsulated in its own
response msg
SMTP: multiple objects
sent in multipart msg
2: Application Layer 56
Mail message format
2: Application Layer 57
Message format: multimedia extensions
MIME: multimedia mail extension, RFC 2045, 2056
additional lines in msg header declare MIME content
type
From: alice@[Link]
MIME version To: bob@[Link]
Subject: Picture of yummy crepe.
method used MIME-Version: 1.0
to encode data Content-Transfer-Encoding: base64
Content-Type: image/jpeg
multimedia data
type, subtype, base64 encoded data .....
parameter declaration .........................
......base64 encoded data
encoded data
2: Application Layer 58
Mail access protocols
SMTP SMTP access user
user
agent protocol agent
2: Application Layer 59
POP3 protocol S: +OK POP3 server ready
C: user bob
authorization phase S: +OK
C: pass hungry
client commands:
S: +OK user successfully logged on
user: declare username
C: list
pass: password
S: 1 498
server responses S: 2 912
+OK S: .
-ERR C: retr 1
S: <message 1 contents>
transaction phase, client: S: .
list: list message numbers C: dele 1
retr: retrieve message by C: retr 2
S: <message 1 contents>
number
S: .
dele: delete
C: dele 2
quit C: quit
S: +OK POP3 server signing off
2: Application Layer 60
POP3 (more) and IMAP
More about POP3 IMAP
Previous example Keep all messages in
uses “download and one place: the server
delete” mode. Allows user to
Bob cannot re-read e-
organize messages in
mail if he changes folders
client IMAP keeps user state
“Download-and-keep”:
across sessions:
copies of messages on names of folders and
different clients mappings between
POP3 is stateless message IDs and
across sessions folder name
2: Application Layer 61
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
2.2 Web and HTTP programming with TCP
2.3 FTP 2.8 Socket
2.4 Electronic Mail programming with
SMTP, POP3, IMAP UDP
2.5 DNS 2.9 Building a Web
server
2: Application Layer 62
DNS: Domain Name System
2: Application Layer 64
Distributed, Hierarchical
Database
Root DNS Servers
m WIDE Tokyo
e NASA Mt View, CA
f Internet Software C. Palo Alto,
CA (and 17 other locations)
13 root name
servers worldwide
b USC-ISI Marina del Rey, CA
l ICANN Los Angeles, CA
2: Application Layer 66
TLD and Authoritative
Servers
Top-level domain (TLD) servers:
responsible for com, org, net, edu, etc, and
all top-level country domains uk, fr, ca, jp.
Network solutions maintains servers for com
TLD
Educause for edu TLD
2: Application Layer 68
Example root DNS server
2
Host at [Link] 3
TLD DNS server
wants IP address 4
for
5
[Link]
local DNS server
[Link]
7 6
1 8
[Link]
2: Application Layer 69
Recursive queries root DNS server
recursive query:
puts burden of 2 3
name resolution on 7 6
contacted name TLD DNS serve
server
heavy load?
local DNS server
5 4
iterated query: [Link]
contacted server 1 8
replies with name of
server to contact authoritative DNS server
“I don’t know this [Link]
requesting host
name, but ask this [Link]
server”
[Link]
2: Application Layer 70
DNS: caching and updating
records
once (any) name server learns mapping, it
caches mapping
cache entries timeout (disappear) after
some time
TLD servers typically cached in local name
servers
• Thus root name servers not often visited
update/notify mechanisms under design by
IETF
RFC 2136
[Link]
2: Application Layer 71
DNS records
DNS: distributed db storing resource records (RR)
RR format: (name, value, type, ttl)
Type=A Type=CNAME
name is hostname name is alias name for some
value is IP address “canonical” (the real) name
Type=NS [Link] is really
name is domain (e.g. [Link]
[Link]) value is canonical name
value is hostname of
Type=MX
authoritative name server
for this domain value is name of mailserver
associated with name
2: Application Layer 72
DNS protocol, messages
DNS protocol : query and reply messages, both with same message format
msg header
identification: 16 bit #
for query, reply to
query uses same #
flags:
query or reply
recursion desired
recursion available
reply is authoritative
2: Application Layer 73
DNS protocol, messages
RRs in
response
to query
records for
authoritative servers
additional “helpful”
info that may be used
2: Application Layer 74
Inserting records into DNS
Example: just created startup “Network Utopia”
Register name [Link] at a registrar
(e.g., Network Solutions)
Need to provide registrar with names and IP addresses
of your authoritative name server (primary and
secondary)
Registrar inserts two RRs into the com TLD server:
2: Application Layer 76
P2P file sharing
Alice chooses one of
it informs central 1
server:
1 3
IP address
2
content 1
2: Application Layer 78
P2P: problems with centralized
directory
Single point of failure file transfer is
Performance decentralized, but
bottleneck locating content is
Copyright highly centralized
infringement
2: Application Layer 79
Query flooding: Gnutella
fully distributed overlay network: graph
no central server edge between peer X
public domain and Y if there’s a TCP
protocol connection
many Gnutella all active peers and
clients implementing edges is overlay net
protocol Edge is not a
physical link
Given peer will
typically be
connected with < 10
overlay neighbors
2: Application Layer 80
Gnutella: protocol
File transfer:
Query message
HTTP
sent over existing TCP
connections
Query
peers forward
QueryHit
Query message
QueryHit e ry Qu
ery
Qu Hit
sent over ery
Qu
reverse
Query
path
QueryHit
Qu
Scalability: er
y
limited scope
flooding
2: Application Layer 81
Gnutella: Peer joining
1. Joining peer X must find some other peer in
Gnutella network: use list of candidate peers
2. X sequentially attempts to make TCP with
peers on list until connection setup with Y
3. X sends Ping message to Y; Y forwards Ping
message.
4. All peers receiving Ping message respond
with Pong message
5. X receives many Pong messages. It can then
setup additional TCP connections
Peer leaving: see homework problem!
2: Application Layer 82
Exploiting heterogeneity: KaZaA
Each peer is either a
group leader or
assigned to a group
leader.
TCP connection
between peer and its
group leader.
TCP connections
between some pairs of
group leaders.
ordinary peer
Group leader tracks
group-leader peer
the content in all its neighoring relationships
2: Application Layer 83
KaZaA: Querying
Each file has a hash and a descriptor
Client sends keyword query to its group
leader
Group leader responds with matches:
For each match: metadata, hash, IP address
If group leader forwards query to other
group leaders, they respond with
matches
Client then selects files for downloading
HTTP requests using hash as identifier sent
to peers holding desired file
2: Application Layer 84
KaZaA tricks
Limitations on simultaneous uploads
Request queuing
Incentive priorities
Parallel downloading
2: Application Layer 85
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
2.2 Web and HTTP programming with TCP
2.3 FTP 2.8 Socket
2.4 Electronic Mail programming with
SMTP, POP3, IMAP UDP
2.5 DNS 2.9 Building a Web
server
2: Application Layer 86
Socket programming
Goal: learn how to build client/server application
that communicate using sockets
2: Application Layer 87
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
controlled by
controlled by process application
application process
developer
developer socket socket
controlled by TCP with TCP with controlled by
buffers, operating
operating buffers, internet system
system variables variables
host or host or
server server
2: Application Layer 88
Socket programming with TCP
Client must contact server When contacted by client,
server process must first server TCP creates new
be running socket for server process
server must have created to communicate with client
socket (door) that allows server to talk
welcomes client’s contact with multiple clients
Client contacts server by: source port numbers
creating client-local TCP used to distinguish
socket clients (more in Chap 3)
specifying IP address, port
number of server process application viewpoint
When client creates socket:
TCP provides reliable, in-order
client TCP establishes transfer of bytes (“pipe”)
connection to server TCP
between client and server
2: Application Layer 89
Stream jargon
A stream is a sequence
of characters that flow
into or out of a process.
An input stream is
attached to some input
source for the process,
e.g., keyboard or socket.
An output stream is
attached to an output
source, e.g., monitor or
socket.
2: Application Layer 90
Socket programming with TCP
keyboard monitor
Example client-server
app:
inFromUser
1) client reads line from input
stream
standard input (inFromUser Client
stream) , sends to server via Process
process
socket (outToServer
stream)
2) server reads line from socket
3) server converts line to
inFromServer
outToServer
output input
uppercase, sends back to stream stream
client
4) client reads, prints modified client TCP
clientSocket
line from socket socket TCP
socket
(inFromServer stream)
to network from network
2: Application Layer 91
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket
2: Application Layer 92
Example: Java client (TCP)
import [Link].*;
import [Link].*;
class TCPClient {
sentence = [Link]();
Send line
to server [Link](sentence + '\n');
[Link]();
}
}
2: Application Layer 94
Example: Java server (TCP)
import [Link].*;
import [Link].*;
class TCPServer {
2: Application Layer 95
Example: Java server (TCP), cont
Create output
stream,
attached DataOutputStream outToClient =
to socket new DataOutputStream([Link]());
Read in line
from socket clientSentence = [Link]();
2: Application Layer 96
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
2.2 Web and HTTP programming with TCP
2.3 FTP 2.8 Socket
2.4 Electronic Mail programming with
SMTP, POP3, IMAP UDP
2.5 DNS 2.9 Building a Web
server
2: Application Layer 97
Socket programming with UDP
UDP: no “connection”
between client and
server
no handshaking
application viewpoint
sender explicitly attaches
UDP provides unreliable transfer
IP address and port of
of groups of bytes (“datagrams”)
destination to each
between client and server
packet
server must extract IP
address, port of sender
from received packet
UDP: transmitted data may
be received out of order,
or lost
2: Application Layer 98
Client/server socket interaction: UDP
Server (running on hostid) Client
create socket,
port=x, for create socket,
clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read request from
serverSocket
write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port number close
clientSocket
2: Application Layer 99
Example: Java client (UDP)
keyboard monitor
inFromUser
input
stream
Client
Process
Input: receives
process
packet (TCP
Output: sends received “byte
packet (TCP sent stream”)
receivePacket
sendPacket
“byte stream”) UDP UDP
packet packet
client UDP
clientSocket
socket UDP
socket
class UDPClient {
public static void main(String args[]) throws Exception
{
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader([Link]));
Create
client socket DatagramSocket clientSocket = new DatagramSocket();
Translate
InetAddress IPAddress = [Link]("hostname");
hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
Create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, [Link]);
Receive [Link](receivePacket);
datagra
m
2: Application Layer 103
Example: Java server (UDP),
cont
String sentence = new String([Link]());
Get IP addr
InetAddress IPAddress = [Link]();
port #, of
sender int port = [Link]();
sendData = [Link]();
Create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, [Link], IPAddress,
port);
Write out
datagram [Link](sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram
2: Application Layer 104
Chapter 2: Application layer
2.1 Principles of 2.6 P2P file sharing
network applications 2.7 Socket
app architectures programming with TCP
app requirements 2.8 Socket
2.2 Web and HTTP
programming with
2.4 Electronic Mail UDP
SMTP, POP3, IMAP 2.9 Building a Web
2.5 DNS server
typical request/reply
control vs. data msgs
message exchange:
in-band, out-of-band
client requests info or
centralized vs.
service
server responds with
decentralized
data, status code stateless vs. stateful
message formats: reliable vs. unreliable msg
headers: fields giving
transfer
“complexity at network
info about data
data: info being edge”
communicated