3rd Edition: Chapter 2
Download
Report
Transcript 3rd Edition: Chapter 2
Chapter 2
Application Layer
A note on the use of these ppt slides:
We’re making these slides freely available to all (faculty, students, readers).
They’re in PowerPoint form so you can add, modify, and delete slides
(including this one) and slide content to suit your needs. They obviously
represent a lot of work on our part. In return for use, we only ask the
following:
If you use these slides (e.g., in a class) in substantially unaltered form,
that you mention their source (after all, we’d like people to use our book!)
If you post any slides in substantially unaltered form on a www site, that
you note that they are adapted from (or perhaps identical to) our slides, and
note our copyright of this material.
Computer Networking:
A Top Down Approach,
4th edition.
Jim Kurose, Keith Ross
Addison-Wesley, July
2007.
Thanks and enjoy! JFK/KWR
All material copyright 1996-2007
J.F Kurose and K.W. Ross, All Rights Reserved
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
2.6 P2P Applications
2.7 Socket programming
with TCP
2.8 Socket programming
with UDP
SMTP, POP3, IMAP
2.5 DNS
2: Application Layer
2
Vocabulary and Term
Client-server paradigm
客户-服务器范式
Peer-to-Peer
对等范式
paradigm
WWW(World Wide Web)
万维网
HTTP(HyperText Transfer Protocol)
超文本传输协议
Persistent HTTP
永久性/持续性HTTP
2: Application Layer
3
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
4
Some typical network applications
e-mail
web
instant messaging
remote login
P2P file sharing
multi-user network games
voice over IP
real-time video
conferencing
grid computing
… …
… …
streaming stored video
clips
2: Application Layer
5
Creating a network application
write programs that
run on (different) end
systems
communicate over network
e.g., web server software
communicates with browser
software
little software written for
devices in network core
application
transport
network
data link
physical
network core devices do
not run user applications
applications on end systems
allows for rapid application
development, propagation
application
transport
network
data link
physical
application
transport
network
data link
physical
2: Application Layer
6
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
7
Application architectures
Client-server
Peer-to-peer (P2P)
Hybrid of client-server and P2P
2: Application Layer
8
C/S Service Infrastructure
request
Server
Client1
response
Client2
Client N
2: Application Layer
9
Client-server architecture
server:
always-on host
permanent IP address
server farms for scaling
clients:
client/server
communicate with server
may be intermittently
connected
may have dynamic IP
addresses
do not communicate directly
with each other
2: Application Layer
10
位于俄勒冈州(Oregon)的Google数据中心
Google公司比利时无冷却器数据中心
2: Application Layer
11
Pure P2P architecture
no always-on server
arbitrary end systems
directly communicate peer-peer
peers are intermittently
connected and change IP
addresses
example: Gnutella
Highly scalable but
difficult to manage
2: Application Layer
12
Gnutella Principles
2: Application Layer
13
Hybrid of client-server and P2P
Skype
voice-over-IP: typical P2P application
centralized server: find address of remote party
client-client connection: direct (not through server)
Instant messaging [QQ]
chatting between two users is P2P
centralized service: client presence detection
/location
• 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
14
P2P:Sample applications
File Sharing
Media
Storage
Distributed computing
2: Application Layer
15
Processes communicating
Process: program running
within a host.
within the 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
16
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
17
Addressing processes
to receive messages,
process must have
identifier
host device has unique
32-bit IP address
Q: does IP address of
host on which process
runs suffice for
identifying the process?
2: Application Layer
18
Addressing processes
to receive messages,
process must have
identifier
host device has unique
32-bit IP address
Q: does IP address of
host on which process
runs suffice for
identifying the
process?
A: many processes can
be running on the same
host
identifier includes both
IP address and port
numbers associated with
process on host.
Example port numbers:
HTTP server: 80
Mail server: 25
to send HTTP message
to gaia.cs.umass.edu web
server:
IP address: 128.119.245.12
Port number: 80
more shortly…
2: Application Layer
19
Application-layer protocol defines
Types of messages
exchanged,
e.g., request, response
Message syntax:
what fields in messages &
how fields are delineated
Message semantics:
meaning of information in
fields
Public-domain protocols:
defined in RFCs
allows for
interoperability (互操作性)
e.g., HTTP, SMTP
Proprietary protocols:
e.g., Skype
Rules for when and how
processes send &
respond to messages
2: Application Layer
20
What transport service does an applications
need?
Data loss
some applications (e.g., audio)
can tolerate some loss.
other applications (e.g., file
transfer, telnet) require 100%
reliable data transfer.
Timing
some applications (e.g.,
Internet telephony,
interactive games)
require low delay to be
“effective”
Bandwidth
some applications (e.g.,
multimedia) require
minimum amount of
bandwidth to be
“effective”
other applications
(“elastic applications ”)
make use of whatever
bandwidth they get
Security
secure service, encryption, data integrity, etc.
2: Application Layer
21
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
22
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,
bandwidth guarantee
Q: why bother? Why is
there a UDP?
2: Application Layer
23
Internet transport protocols services
Goal: data transfer between end systems
Handshaking
setup (prepare for) data transfer ahead of time
Hello, hello back human protocol
set up “state” in two communicating hosts
TCP - Transmission Control Protocol
(传输控制协议)
2: Application
Introduction
Layer
24
1-24
connection-oriented service
TCP service
Reliability control(可靠性控制)
Acknowledgements(应答) and retransmissions
(重传)
flow control(流量控制)
sender won’t overwhelm receiver
congestion control(拥塞控制)
senders “slow down sending rate” when network
congested
2: Application
Introduction
Layer
25
1-25
Applications using TCP
HTTP (Web)
FTP (file transfer)
Telnet (remote login)
SMTP (email)
2: Application
Introduction
Layer
26
1-26
Connectionless service
Goal: data transfer between end systems
same as before!
UDP [RFC 768] - User Datagram Protocol
(用户数据报协议) :Internet’s connectionless
service
unreliable data transfer
no flow control
no congestion control
2: Application
Introduction
Layer
27
1-27
Applications using UDP
streaming media(流媒体)
Teleconferencing(视频会议)
DNS(Domain Name Service (域名服务)
Internet telephony(网络电话)
2: Application
Introduction
Layer
28
1-28
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
29
Chapter 2: Application layer
2.1 Principles of
network applications
app architectures
app requirements
2.2 Web and HTTP
2.3 FTP
2.6 P2P file sharing
2.7 Socket programming
with TCP
2.8 Socket programming
with UDP
2.4 Electronic Mail
SMTP, POP3, IMAP
2.5 DNS
2: Application Layer
30
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 (Uniform
Resource Locators, 统一资源定位符)
Example URL:
www.someschool.edu/someDept/pic.gif
host name
path name
2: Application Layer
31
Client-Server (Browser-Server)
Architecture
browser
Web Server
Client Software
1990:Tim. Berners-lee wrote the
first web client (browser-editor)
and server.
1993: Mark Andreesen in US
“Mosaic” Netscape Navigator
IE
Mozilla (Netscape 6)
Tecent
the Director of the
World Wide Web
Consortium
2: Application Layer
32
HTTP overview
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
33
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
34
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
35
Nonpersistent HTTP
Suppose user enters URL
(contains text,
references to 10
jpeg images)
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
2: Application Layer
36
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
37
Non-Persistent HTTP: Response time
Definition of RTT: time to send a
small packet to travel from
client to server and back.
Response time:
initiate TCP
one RTT (round trip time,往返 connection
时延) to initiate TCP connection
RTT
request
one RTT for HTTP request and
file
first few bytes of HTTP
RTT
response to return
file transmission time
file
total = 2RTT+transmit time
received
time
time to
transmit
file
time
2: Application Layer
38
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
39
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(回车),
(extra carriage return, line feed)
line feed(换行)
indicates end
of message
2: Application Layer
40
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
41
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
42
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
43
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
44
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
45
User-server state: cookies
Example:
Susan always access
Internet always from PC
visits specific e1) cookie header line of
HTTP response message
commerce site for first
2) cookie header line in
time
HTTP request message
when initial HTTP
3) cookie file kept on
user’s host, managed by
requests arrives at site,
user’s browser
site creates:
4) back-end database at
unique ID
Web site
entry in backend
database for ID
Many major Web sites
use cookies
Four components:
2: Application Layer
46
Cookies: keeping “state” (cont.)
client
ebay 8734
cookie file
ebay 8734
amazon 1678
server
usual http request msg
usual http response
Set-cookie: 1678
usual http request msg
cookie: 1678
one week later:
ebay 8734
amazon 1678
usual http response msg
usual http request msg
cookie: 1678
usual http response msg
Amazon server
creates ID
1678 for user create
entry
cookiespecific
action
access
access
backend
database
cookiespectific
action
2: Application Layer
47
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
How to keep “state”:
protocol endpoints: maintain state
at sender/receiver over multiple
transactions
cookies: http messages carry state
2: Application Layer
48
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
49
How to configure a Proxy?
2: Application Layer
50
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
51
Caching example
origin
servers
Assumptions
average object size = 1Mbps
average 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
utilization on LAN = 15%
public
Internet
15 Mbps
access link
institutional
network
100 Mbps LAN
utilization on access link = 100%
total delay
= Internet delay +
access delay + LAN delay
= 2 sec + minutes + milliseconds
No institutional
cache
2: Application Layer
52
Caching example (cont.)
Origin servers
possible solution
increase bandwidth of access
link to, say, 100 Mbps
consequence
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
100 Mbps
access link
Total delay
institutional
network
100 Mbps LAN
No Institutional cache
2: Application Layer
53
Caching example (cont.)
origin
servers
possible solution: install cache
suppose hit rate is 0.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 + .4*milliseconds < 1.4
secs
15 Mbps
access link
institutional
network
100 Mbps LAN
Institutional
cache
2: Application Layer
54
Homework
Reviews:1,6
Problems:5
Discussion:8
2: Application Layer
55
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
56
Vocabulary and Term
FTP (File Transfer Protocol
文件传输协议
)
Control Connection/Data Connection
控制连接/数据连接
2: Application Layer
57
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
ftp://ftp.gimp.org
client/server model
client: side that initiates transfer (either to/from remote)
server: remote host
RFC 959
ftp server: keep user’s state (stateless?)
2: Application Layer
58
Client
FTP Now
SmartFTP
CuteFTP
Resume from breakpoint (断点续传)
Directory Operation
Smart Keep Alive
Automatic Update
CuteFTP Pro
SSL or SSH2
Directory Synchronization (目录同步)
Multiple Protocols (FTP、SFTP、HTTP、HTTPS)
Simultaneous Multiple Sites
2: Application Layer
59
Server
Super Ftp Server
WS-FTP Server
Quick Easy FTP Server
FTP Serv-U
2: Application Layer
60
FTP: separate control, data connections
FTP client contacts FTP server
TCP control connection
port 21
at port 21, TCP is transport
protocol
TCP data connection
FTP
FTP
port 20
client authorized over control
client
server
connection
client browses remote
server opens another TCP
directory by sending commands
data connection to transfer
over control connection.
another file.
when server receives file
control connection: “out of
transfer command, server
band”
opens 2nd TCP connection (for
FTP server maintains “state”:
file) to client
current directory, earlier
after transferring one file,
authentication
server closes data connection.
2: Application Layer
61
Two connections: ports
control connection
Well-known port: 21
data connection
Well-known port 20
- However on the Server Side, and temporary
port No. at Client Side
2: Application Layer
62
FTP Commands
FTP [host]
Example: %ftp ftp.nudt.edu.cn
username:test -login with real name
password:******
or:
username:anonymous
password:[email protected]
2: Application Layer
63
Anonymous FTP
[01]
[02]
[03]
[04]
[05]
[06]
[07]
[08]
[09]
[10]
[11]
[12]
ftp nic.ddn.mil
connected to nic.ddn.mil
220 nic FTP server (Sunos 4.1)ready.
Name: anonymous
331 Guest login ok, send ident as password.
Password: [email protected]
230 Guest login ok, access restrictions apply.
ftp> cd rfc
250 CWD command successful.
ftp> get rfc1261.txt nicinfo
200 PORT command successful.
150 ASCII data connection for rfc1261.txt
(128.36.12.27,1401) (4318 bytes).
[13] 226 ASCII Transfer complete.
local: nicinfo remote: rfc1261.txt
4488 bytes received in 15 seconds (0.3 Kbytes/s).
[14] ftp> quit
[15] 221 Goodbye.
2: Application Layer
64
FTP commands, responses
Sample commands:
sent as ASCII text over
control channel
USER username
PASS password
LIST return list of file in
Sample return codes
status code and phrase (as in
current directory
RETR filename retrieves
(gets) file
STOR filename stores
(puts) file onto remote
host
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
65
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
66
Vocabulary and Term
EMAIL(Electronic Mail)
电子邮件
SMTP(Simple Mail Transfer Protocol)
简单邮件传输协议
POP3(Post Office Protocol Version 3)
邮局协议-版本3
IMAP4(Internet Mail Access Protocol
Version 4)
互联网邮件访问协议-版本4
Web Mail
2: Application Layer
67
Email History-1
[[email protected]]
[[email protected]]
1970s: Invention
In
the early 1970's, Engineer from BBN
Company Ray Tomlinson chose the "commercial
at" symbol to combine the user and host names,
and "user@host" is the standard for email
addressing .
Larry Roberts of IPTO wrote RD in one threeday weekend to sort and order email headers
by subject and date in their Inbox, and to read,
save, and delete messages in the order they
wished.
2: Application Layer
68
Email History-2
1980s: Development
Mid-term in 1980s: Spread with the PC;
1988: Steve Dorner developed Eudora- the
first mail management with GUI( Graphics User
Interface);
1989: Lotus (莲花)Company released 35000
Lotus Notes email systems.
2: Application Layer
69
Email History-3
1990s:
prevail(鼎盛)
Mid-term in 1990s: Spread quickly with the
WWW
1996:Microsoft Outlook 1.0
1998: Microsoft Acquires (收购) Hotmail
Success of Hotmail led to Email Service by
Yahoo!, netscape,Exicite , Lycos, [Sina,
Sohu,…] Portal sites (门户网站) and
companies.
2: Application Layer
70
Email History-4
New Century
2011: 40th anniversary
1995: Hotmail (free email)
2004 :Google’s GMail has Giga-byte Mailbox
New Competitions
… … …
Email plays more important role in our life and
its security problems become prominent.
2: Application Layer
71
Features of Email
Asynchronous Communication Media
between People
people send and read messages when it is
convenient for them, not at the same time
Comprehensive Media
include text, images, sound and even video.
To communicate ideas, advertisement, file
sharing,…
2: Application Layer
72
Electronic Mail
outgoing
message queue
Three major components:
User agents
Mail servers
SMTP (Simple Mail Transfer
user mailbox
user
agent
mail
server
SMTP
Protocol)
User Agent
SMTP
a.k.a. “mail reader”
composing, editing, reading
mail
mail messages
server
e.g., Eudora, Outlook, elm,
Mozilla Thunderbird
outgoing, incoming messages
stored on server
user
SMTP
user
agent
mail
server
user
agent
user
agent
user
agent
agent
2: Application Layer
73
Electronic Mail: mail servers
user
agent
Mail Servers
mailbox contains incoming
messages for user
message queue of outgoing
(to be sent) mail messages
SMTP Protocol between mail
servers to send email
messages
client: sending mail
server
“server”: receiving mail
server
mail
server
SMTP
SMTP
mail
server
user
agent
SMTP
user
agent
mail
server
user
agent
user
agent
user
agent
2: Application Layer
74
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
messages must be in 7-bit ASCII
2: Application Layer
75
Scenario: Alice sends message to Bob
1) Alice uses UA to compose
message and “send to”
[email protected]
2) Alice’s UA sends message
to her mail server; message
placed in message queue
3) Client side of SMTP opens
TCP connection with Bob’s
mail server
1
user
agent
2
mail
server
3
4) SMTP client sends Alice’s
message over the TCP
connection
5) Bob’s mail server places the
message in Bob’s mailbox
6) Bob invokes his user agent
to read message
mail
server
4
5
6
user
agent
2: Application Layer
76
Sample SMTP interaction
S:
C:
S:
C:
S:
C:
S:
C:
S:
C:
C:
C:
S:
C:
S:
220 hamburger.edu
HELO crepes.fr
250 Hello crepes.fr, pleased to meet you
MAIL FROM: <[email protected]>
250 [email protected]... Sender ok
RCPT TO: <[email protected]>
250 [email protected] ... Recipient ok
DATA
354 Enter mail, end with "." on a line by itself
Do you like ketchup?
How about pickles?
.
250 Message accepted for delivery
QUIT
221 hamburger.edu closing connection
2: Application Layer
77
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
78
SMTP: Comparison with HTTP:
SMTP uses persistent
connections
SMTP requires
message (header &
body) to be in 7-bit
ASCII, however no
such requirement in
http
SMTP server uses
CRLF. to determine
end of message
HTTP: pull protocol
SMTP: push protocol
both have ASCII
command/response
interaction, status
codes
HTTP: each object
encapsulated in its own
response message,
SMTP: multiple
objects sent in
multipart message
2: Application Layer
79
Mail message format
SMTP: protocol for
exchanging email
messages
RFC 822: standard for
text message format:
header lines, e.g.,
header
blank
line
body
To:
From:
Subject:
body
the “message”, ASCII
characters only
2: Application Layer
80
Message format: multimedia extensions
MIME: multimedia mail extension, RFC 2045, 2056
additional lines in message header declare MIME content type
MIME version
method used
to encode data
multimedia data
type, subtype,
parameter declaration
encoded data
From: [email protected]
To: [email protected]
Subject: Picture of yummy crepe.
MIME-Version: 1.0
Content-Transfer-Encoding: base64
Content-Type: image/jpeg
base64 encoded data .....
.........................
......base64 encoded data
2: Application Layer
81
MIME
RFC 2045
(MIME) Part One:
Format of Internet Message Bodies
RFC 2046
(MIME) Part Two:
Media Types
MIME
designed to be fully compatible with existing electronic
mail protocols – SMTP, POP and IMAP.
not just restricted to email, it is now used in HTTP to
deliver audio, video, etc.
2: Application Layer
82
Mail access protocols
user
agent
SMTP
SMTP
sender’s mail
server
access
protocol
user
agent
receiver’s mail
server
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 messages on server
HTTP: Gmail, Hotmail, Yahoo! Mail, etc.
2: Application Layer
83
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 No.
dele: delete
quit:
S:
C:
S:
C:
S:
+OK POP3 server ready
user bob
+OK
pass hungry
+OK user successfully logged
C:
S:
S:
S:
C:
S:
S:
C:
C:
S:
S:
C:
C:
S:
list
1 498
2 912
.
retr 1
<message 1 contents>
.
dele 1
retr 2
<message 1 contents>
.
dele 2
quit
+OK POP3 server signing off
2: Application Layer
on
84
POP3 (more) and IMAP
More about POP3
Previous example uses
“download and delete”
mode.
Bob cannot re-read email if he changes
client
“Download-and-keep”:
copies of messages on
different clients
POP3 is stateless
across sessions
IMAP
Keep all messages in
one place: the server
Allows user to
organize messages in
folders
IMAP keeps user state
across sessions:
names of folders and
mappings between
message IDs and folder
name
2: Application Layer
85
IMAP: Why?
Using POP3
downloaded his messages to the local machine
he can create mail folders and move the
downloaded messages into the folders.
delete messages, move messages across
folders, and search for messages
BUT for nomadic(到处游动的) user
who would prefer to maintain a folder hierarchy
on a remote server that can be accessed by
from any computer
2: Application Layer
86
IMAP
IMAP uses TCP on port 143
Allows user to organize messages in folders
Operate system mailbox in server like user
mailbox in client
Can obtain components of message
A wireless pr low-speed user can only fetch
text part of the mail in MIME format, while
keeping the video/image parts in the server
2: Application Layer
87
WebMail: email with http
San Zhang
Ming Xu
Gmail
Hotmail
Receiver
Receiver
Receiver
User
Agent
User
UserAgent
Agent
Originator
Originator
Originator
UserAgent
Agent
User
User
Agent
http
http
Mail
server
mail.nudt.edu
Mail
Server
SMTP
mail.xd..edu
2: Application Layer
88
The Problems in Mail System
SPAM
Mail Phishing
Mail Virus/Worm
Privacy /confidentiality
2: Application Layer
89
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
90
DNS: Domain Name System
People: many identifiers:
SSN, name, passport #
Internet hosts, routers:
Domain Name System:
distributed database
implemented in hierarchy of
many name servers
IP address (32 bit) - used
application-layer protocol
for addressing datagrams
“name”, e.g.,
www.yahoo.com
- used by humans
Q: How to map between IP
addresses and name ?
host, routers, name servers to
communicate to resolve names
(address/name translation)
note: core Internet
function, implemented as
application-layer protocol
complexity at network’s
“edge”
2: Application Layer
91
DNS
DNS services
hostname to IP
address translation
Basis for Http, SMTP,
etc.
host aliasing
Canonical, alias names
mail server aliasing
load distribution
replicated Web
servers: set of IP
addresses for one
canonical name
Why not centralize DNS?
single point of failure
traffic volume
distant centralized
database
maintenance
doesn’t scale!
2: Application Layer
92
Distributed, hierarchical database
Root DNS Servers
com DNS servers
yahoo.com
amazon.com
DNS servers DNS servers
org DNS servers
pbs.org
DNS servers
edu DNS servers
poly.edu
umass.edu
DNS serversDNS servers
Client wants IP for www.amazon.com; 1st approx:
Client queries a root server to find com DNS server
Client queries com DNS server to get amazon.com
DNS server
Client queries amazon.com DNS server to get IP
address for www.amazon.com
2: Application Layer
93
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
a Verisign, Dulles, VA
c Cogent, Herndon, VA (also LA)
d U Maryland College Park, MD
g US DoD Vienna, VA
h ARL Aberdeen, MD
j Verisign, ( 21 locations)
e NASA Mt View, CA
f Internet Software C. Palo Alto,
k RIPE London (also 16 other locations)
i Autonomica, Stockholm (plus
28 other locations)
m WIDE Tokyo (also Seoul,
Paris, SF)
CA (and 36 other locations)
13 root name
servers worldwide
b USC-ISI Marina del Rey, CA
l ICANN Los Angeles, CA
2: Application Layer
94
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 maintains servers for edu TLD
Authoritative DNS servers:
organization’s DNS servers, providing
authoritative hostname to IP mappings for
organization’s servers (e.g., Web, mail).
can be maintained by organization or service
provider
2: Application Layer
95
Local Name Server
does not strictly belong to hierarchy
each ISP (residential ISP, company,
university) has one.
also called “default name server”
when host makes DNS query, query is sent
to its local DNS server
acts as proxy, forwards query into hierarchy
2: Application Layer
96
DNS name
resolution example
root DNS server
2
Host at cis.poly.edu
3
wants IP address for
gaia.cs.umass.edu
iterated query:
contacted server
replies with name of
server to contact
“I don’t know this
name, but ask this
server”
TLD DNS server
4
5
local DNS server
dns.poly.edu
1
8
requesting host
7
6
authoritative DNS server
dns.cs.umass.edu
cis.poly.edu
gaia.cs.umass.edu
2: Application Layer
97
DNS name
resolution example
root DNS server
2
recursive query:
3
7
6
TLD DNS server
puts burden of name
resolution on contacted
name server
local DNS server
dns.poly.edu
heavy load?
1
5
4
8
requesting host
authoritative DNS server
dns.cs.umass.edu
cis.poly.edu
gaia.cs.umass.edu
2: Application Layer
98
The Combination of Recursion and Iteration
Root DNS Server
dns.com
③
⑤
Local DNS server
dns.y.abc.com
④
Local DNS server
Local DNS server
⑥
②
dns.abc.com
⑦
dns.xyz.com
⑧
IP(t.y.abc.com)
= (198.54.23.15)
t.y.abc.com
①
IP(t.y.abc.com)=?
m.xyz.com
2: Application Layer
99
DNS records
DNS: distributed DB storing resource records (RR)
RR format: (name,
Type=A
name is hostname
value is IP address
Type=NS
name is domain (e.g.
foo.com)
value is hostname of
authoritative name
server for this domain
value, type, TTL)
Type=CNAME
name is alias name for some
“canonical” (the real) name
www.ibm.com is really
servereast.backup2.ibm.com
value is canonical name
Type=MX
value is name of mailserver
associated with name
2: Application Layer
100
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
101
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
2: Application Layer
102
Inserting records into DNS
example: new startup “Network Utopia”
register name networkuptopia.com at DNS
(e.g., Network Solutions Inc.)
registrar
provide names, IP addresses of authoritative name server
(primary and secondary)
registrar inserts two RRs into com TLD server:
(networkutopia.com, dns1.networkutopia.com, NS)
(dns1.networkutopia.com, 212.212.212.1, A)
create authoritative server Type A record for
www.networkuptopia.com; Type MX record for
networkutopia.com
How do people get IP address of your Web site?
2: Application Layer
103
Review
DNS (Domain Name Service)
DNS is an infrastructural service by the
Internet like routing and data forwarding
Mapping between domain name and IP
address
http://www.google.com
DNS
216.239.57.99
2: Application Layer
104
Domain Space
Root
Top Level Domain Name
… coop info biz aero com net org edu gov mil int cn uk …
Authoritative Domain Name
cctv… ibm hp
mot
Local Domain Name
… hk js sh bj org net gov edu com ac
Local Domain Name
mail
Local Domain Name
…
tsinghua pku fudan sjtu seu
mail csnetl ep
…
2: Application Layer
105
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
http://www.ietf.org/html.charters/dnsind-charter.html
2: Application Layer
106
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
107
P2P file sharing
Example
Alice runs P2P client
application on her
notebook computer
intermittently
connects to Internet;
gets new IP address
for each connection
asks for “Hey Jude”
application displays
other peers that have
copy of Hey Jude.
Alice chooses one of
the peers, Bob.
file is copied from
Bob’s PC to Alice’s
notebook: HTTP
while Alice downloads,
other users uploading
from Alice.
Alice’s peer is both a
Web client and a
transient Web server.
All peers are servers =
highly scalable!
2: Application Layer
108
Content for the Section
1.Overview of Peer-to-Peer Applications
1.1 What is P2P ?
1.2 Why is P2P so popular?
1.3 Who are P2P applications?
2.How does P2P work?
2.1 Centralized: Napster
2.2 Fully Distributed :Gnutella
2.3 Hierarchical: KaZaA
2.4 Bit Torrent (BT) [Supplementary,补充的]
3.Where to go:
Issues and Future Directions
2: Application Layer
109
Vocabulary and Term
Peer
对等体
P2P (Peer-to-Peer) Application/ Network
对等应用、对等网络
Centralized/Distributed/Hierarchical
集中的、分布的、层次的
Free Riding
免费搭车
2: Application Layer
110
Content for the Section
1.Overview of Peer-to-Peer Applications
1.1 What is P2P ?
1.2 Why is P2P so popular?
1.3 Who are P2P applications?
2.How does P2P work?
2.1 Centralized: Napster
2.2Fully Distributed :Gnutella
2.3 Hierarchical: KaZaA
2.4 Bit Torrent (BT) [Supplementary,补充的]
3.Where to go:
Issues and Future Directions
2: Application Layer
111
Client-Server Mode
F bits
d4
upload rate us
Internet
d3
d1
d2
Server becomes bottleneck
(CPU/Bandwidth)
2: Application Layer
112
Peer-to-Peer Mode
Different Hosts Download from Multiple Sources
F bits
D
d4
u4
upload rate us
A
Internet
d3
d1
u1
d2
u2
Pieces of one file can be
downloaded from Multiple Sources
u3
C
B
2: Application Layer
113
Why is P2P so Popular?
P2P networks generate more traffic than any
other internet application
2/3 of all bandwidth on some backbones
2: Application Layer
114
Killer Application
1st generation: “raw” Internet
Killer Application: EMAIL
2nd generation: the Web
Killer Application: WWW
Client –Server Mode
3rd generation: P2P Network
Killer Application: P2P Applications
Peer-to-Peer Mode: Every PC acts as active participant
to provide service (file sharing, BLOG/PODCAST)
Peer-to-Peer Mode: “I work for everyone, and everyone
for me”(我为人人,人人为我)
2: Application Layer
115
Advantages of P2P model
High Performance(高性能)
Help find the shared resources
Speed up the file distribution
Reliability (可靠性)
Client-server mode: The whole network will depend on
the highly loaded server to function properly
There is zero reliance on centralized serviced or
resources for operations
Scalability (扩展性)
In client-server mode: there is a higher demand for
computing power, storage space, and bandwidth
associated with the server-side.
2: Application Layer
116
Who are P2P Applications?
Video Streaming
Advanced
Applications
VOIP
PPLive
Skype
Downloading
BitTorrent
File Sharing
Basic
Applications
Napster
2001
2003
2004
2005
2: Application Layer
117
Who are P2P Applications?
File Share
KuGoo(酷狗),PPGou
P2P Download Accelerator(加速器)
2: Application Layer
118
Comparing Client-server, P2P architectures
Question : How much time distribute file
initially at one server to N other computers?
us: server upload
bandwidth
Server
us
File, size F
dN
uN
u1
d1
u2
ui: client/peer i
upload bandwidth
d2
di: client/peer i
download bandwidth
Network (with
abundant bandwidth)
2: Application Layer
119
Client-server: file distribution time
server sequentially
sends N copies:
NF/us time
client i takes F/di
time to download
Server
F
us
dN
u1 d1 u2
d2
Network (with
abundant bandwidth)
uN
Time to distribute F
to N clients using = dcs = max { NF/us, F/min(di) }
i
client/server approach
increases linearly in N
(for large N) 2: Application Layer
120
P2P: file distribution time
server must send one
Server
F
u1 d1 u2
d2
copy: F/us time
us
client i takes F/di time
Network (with
dN
to download
abundant bandwidth)
uN
NF bits must be
downloaded (aggregate)
fastest possible upload rate (assuming
all nodes sending file chunks to same
peer): us + Sui
i=1,N
dP2P = max { F/us, F/min(di) , NF/(us + Sui) }
i
i=1,N
2: Application Layer
121
File distribution time
2: Application Layer
122
Centralized: Napster
Napster history: the rise
January 1999: Napster version 1.0
May 1999: company founded
2000: 80 million users
Shawn Fanning
Napster history: the fall
Mid 2001: out of business due to Northeastern freshman(18)
lawsuits(诉讼)against copyright
Napster history: the resurrection(复苏)
2003: Napster reconstituted as a pay service
2007: still lots of file sharing going on
2: Application Layer
123
Napster Technology: Directory Service
User installing the software
Client1 contacts Napster server
Provides a list of music files it will share
… and Napster’s central server updates the directory
Client2 searches a music by title or performer
Napster identifies online clients with the file
… and provides IP addresses
Client2 requests the file from the chosen supplier
Supplier transmits the file to the client
Both client and supplier report status to Napster
2: Application Layer
124
P2P: problems with centralized directory
file transfer is decentralized(分散的), but locating content
is highly centralized
Single point of failure
System has single points of entry; one fails could
bring whole system down
Performance bottleneck
Broken links, out of date (过期的) information
Copyright infringement (版权侵害)
So, later P2P systems were more distributed
Gnutella went to the other extreme…
2: Application Layer
125
Chapter 2: Application layer
2.1 Principles of
network applications
2.2 Web and HTTP
2.3 FTP
2.4 Electronic Mail
2.6 P2P file sharing
2.7 Socket programming
with TCP
2.8 Socket programming
with UDP
SMTP, POP3, IMAP
2.5 DNS
2: Application Layer
126
Socket programming
Goal: learn how to build client/server application that
communicate using sockets
Socket API
introduced in BSD4.1 UNIX,
1981
explicitly created, used,
released by applications
client/server paradigm
two types of transport
service via socket API:
unreliable datagram
reliable, byte streamoriented
socket
a host-local,
application-created,
OS-controlled interface
(a “door”) into which
application process can
both send and
receive messages to/from
another application
process
2: Application Layer
127
Socket-programming using TCP
Socket: a door between application process and endend-transport protocol (UCP or TCP)
TCP service: reliable transfer of byte Streams from
one process to another
controlled by
application
developer
controlled by
operating
system
process
process
socket
TCP with
buffers,
variables
host or
server
internet
socket
TCP with
buffers,
variables
controlled by
application
developer
controlled by
operating
system
host or
server
2: Application Layer
128
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 viaTCP
When contacted by client,
server TCP creates new socket
for server process to
communicate with client
allows server to talk with
multiple clients
source port numbers used to
distinguish clients (more in
Chapter 3)
application viewpoint
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server
2: Application Layer
129
Client/server socket interaction: TCP
Server (running on hostid)
Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
TCP
wait for incoming
connection request connection
connectionSocket =
welcomeSocket.accept()
read request from
connectionSocket
write reply to
connectionSocket
close
connectionSocket
setup
create socket,
connect to hostid, port=x
clientSocket =
Socket()
send request using
clientSocket
read reply from
clientSocket
close
clientSocket
2: Application Layer
130
Stream jargon
keyboard
monitor
output
stream
inFromServer
Client
Process
process
input
stream
outToServer
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.
inFromUser
A stream is a sequence of
input
stream
client
TCP
clientSocket
socket
to netw ork
TCP
socket
from netw ork
2: Application Layer
131
Socket programming with TCP
Example client-server application:
1) Client reads line from standard input (inFromUser stream)
, sends to server via socket (outToServer stream)
2) Server reads line from socket
3) Server converts line to uppercase, sends back to client
4) Client reads, prints modified line from socket
(inFromServer stream)
2: Application Layer
132
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
2: Application Layer
133
Example: Java client (TCP), cont.
Create
input stream
attached to socket
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
Send line
to server
outToServer.writeBytes(sentence + '\n');
Read line
from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
2: Application Layer
134
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
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()));
2: Application Layer
135
Example: Java server (TCP), cont
Create output
stream, attached
to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
Write out line
to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
End of while loop,
loop back and wait for
another client connection
2: Application Layer
136
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
137
Socket programming with UDP
UDP: no “connection” between
client and server
no handshaking
sender explicitly attaches
IP address and port of
destination to each packet
server must extract IP
address, port of sender
from received packet
application viewpoint
UDP provides unreliable transfer
of groups of bytes (“datagrams”)
between client and server
UDP: transmitted data may be
received out of order, or
lost
2: Application Layer
138
Client/server socket interaction: UDP
Server (running on hostid)
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port number
Client
create socket,
clientSocket =
DatagramSocket()
Create, address (hostid, port=x,
send datagram request
using clientSocket
read reply from
clientSocket
close
clientSocket
2: Application Layer
139
Example: Java client (UDP)
input
stream
Client
process
monitor
inFromUser
keyboard
Process
Input: receives
packet (recall
thatTCP received
“byte stream”)
UDP
packet
receivePacket
packet (recall
that TCP sent
“byte stream”)
sendPacket
Output: sends
client
UDP
clientSocket
socket
to netw ork
UDP
packet
UDP
socket
f rom netw ork
2: Application Layer
140
Example: Java client (UDP)
import java.io.*;
import java.net.*;
Create
input stream
Create
client socket
Translate
hostname to IP
address using DNS
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();
2: Application Layer
141
Example: Java client (UDP), cont.
Create datagram
with data-to-send,
length, IP addr, port
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
Send datagram
to server
clientSocket.send(sendPacket);
Read datagram
from server
clientSocket.receive(receivePacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
2: Application Layer
142
Example: Java server (UDP)
import java.io.*;
import java.net.*;
Create
datagram socket
at port 9876
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)
{
Create space for
received datagram
Receive
datagram
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
2: Application Layer
143
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of
sender
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
Create datagram
to send to client
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram
to socket
serverSocket.send(sendPacket);
}
}
}
End of while loop,
loop back and wait for
another datagram
2: Application Layer
144
Chapter 2: Summary
our study of network apps now complete!
application architectures
client-server
P2P
hybrid
application service
requirements:
reliability, bandwidth,
delay
specific protocols:
HTTP
FTP
SMTP, POP, IMAP
DNS
P2P: BitTorrent, Skype
socket programming
Internet transport
service model
connection-oriented,
reliable: TCP
unreliable, datagrams: UDP
2: Application Layer
145
Chapter 2: Summary
Most importantly: learned about protocols
typical request/reply
message exchange:
client requests info or
service
server responds with
data, status code
message formats:
headers: fields giving
info about data
data: info being
communicated
Important themes:
control vs. data msgs
in-band, out-of-band
centralized vs.
decentralized
stateless vs. stateful
reliable vs. unreliable
msg transfer
“complexity at network
edge”
2: Application Layer
146
Creativity
TextMultimedia/HyperTextHyperMedi
a Networked HyperMedia
Non-persistent HTTP Persistent without
pipelining Persistent with pipelining
C/S FTP with “resume” function
NetAnts at Clients Side
Multiple Server Peer-to-Peer
2: Application Layer
147
网络协议
应用层: DNS, FTP, ENRP,HTTP, IMAP, IIRC, NNTP,
POP3, SIP, SMTP, SNMP, SSH, Telnet, BitTorrent, DHCP
...
传输层: DCCP, SCTP, TCP, RTP, UDP, IL, RUDP, ...
网络层: IPv4, IPv6...
数据链路层: 以太网, Wi-Fi, 令牌环, MPLS, PPP ...
物理层: RS-232, EIA-422, RS-449, EIA-485, 10BASE2,
10BASE-T ...
2: Application Layer
148