Chapter 2
Application Layer
A note on the use of these ppt slides: Computer
We’re making these slides freely available to all (faculty, students, readers).
They’re in PowerPoint form so you see the animations; and can add, modify, Networking: A
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 Top Down
ask the following:
If you use these slides (e.g., in a class) that you mention their source Approach
(after all, we’d like people to use our book!)
If you post any slides on a www site, that you note that they are adapted
6th edition
from (or perhaps identical to) our slides, and note our copyright of this Jim Kurose, Keith Ross
material. Addison-Wesley
Thanks and enjoy! JFK/KWR March 2012
All material copyright 1996-2012
J.F Kurose and K.W. Ross, All Rights Reserved
Application Layer 2-1
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
2.2 Web and HTTP with UDP and TCP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-2
Chapter 2: application layer
our goals: learn about protocols by
conceptual, examining popular
implementation aspects application-level
of network application protocols
protocols HTTP
transport-layer FTP
service models SMTP / POP3 / IMAP
client-server DNS
paradigm creating network
peer-to-peer applications
paradigm socket API
Application Layer 2-3
Some network apps
e-mail voice over IP (e.g., Skype)
web real-time video
text messaging conferencing
remote login social networking
P2P file sharing search
multi-user network games …
streaming stored video …
(YouTube, Hulu, Netflix)
Application Layer 2-4
Creating a network app application
transport
network
data link
write programs that: physical
run on (different) end systems
communicate over network
e.g., web server software
communicates with browser
software
no need to write software for application
network-core devices transport
network
application
data link
network-core devices do not physical transport
network
run user applications data link
physical
applications on end systems
allows for rapid app
development, propagation
Application Layer 2-5
Application architectures
possible structure of applications:
client-server
peer-to-peer (P2P)
Application Layer 2-6
Client-server architecture
server:
always-on host
permanent IP address
data centers for scaling
clients:
communicate with server
client/server may be intermittently
connected
may have dynamic IP
addresses
do not communicate directly
with each other
Application Layer 2-7
P2P architecture
no always-on server peer-peer
arbitrary end systems
directly communicate
peers request service from
other peers, provide service
in return to other peers
self scalability – new
peers bring new service
capacity, as well as new
service demands
peers are intermittently
connected and change IP
addresses
complex management
Application Layer 2-8
Processes communicating
process: program running clients, servers
within a host client process: process that
within same host, two initiates communication
processes communicate server process: process
using inter-process that waits to be contacted
communication (defined by
OS)
processes in different hosts
communicate by aside: applications with P2P
exchanging messages architectures have client
processes & server
processes
Application Layer 2-9
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 to deliver message to socket at receiving
process
application application
socket controlled by
process process app developer
transport transport
network network controlled
link
by OS
link Internet
physical physical
Application Layer 2-10
Addressing processes
to receive messages, process identifier includes both IP
must have identifier address and port numbers
host device has unique 32- associated with process on
bit IP address host.
Q: does IP address of host example port numbers:
on which process runs HTTP server: 80
suffice for identifying the mail server: 25
process? to send HTTP message to
A: no, many processes gaia.cs.umass.edu web
can be running on same server:
host IP address: 128.119.245.12
port number: 80
more shortly…
Application Layer 2-11
App-layer protocol defines
types of messages open protocols:
exchanged, defined in RFCs
e.g., request, response allows for interoperability
message syntax: e.g., HTTP, SMTP
what fields in messages proprietary protocols:
& how fields are e.g., Skype
delineated
message semantics
meaning of information
in fields
rules for when and how
processes send & respond
to messages
Application Layer 2-12
What transport service does an app need?
data integrity throughput
some apps (e.g., file transfer, some apps (e.g.,
web transactions) require multimedia) require
100% reliable data transfer minimum amount of
other apps (e.g., audio) can throughput to be “ effective
tolerate some loss ”
other apps (“ elastic apps” )
timing make use of whatever
throughput they get
some apps (e.g., Internet
telephony, interactive security
games) require low delay
encryption, data integrity,
to be “ effective”
…
Application Layer 2-13
Transport service requirements: common apps
application data loss throughput time sensitive
file transfer no loss elastic no
e-mail no loss elastic no
Web documents no loss elastic no
real-time audio/video loss-tolerant audio: 5kbps-1Mbps yes, 100’s msec
video:10kbps-5Mbps
stored audio/video loss-tolerant same as above yes, few secs
interactive games loss-tolerant few kbps up yes, 100’s msec
text messaging no loss elastic yes and no
Application Layer 2-14
Internet transport protocols services
TCP service: UDP service:
reliable transport between unreliable data transfer
sending and receiving between sending and
process receiving process
flow control: sender won’t does not provide:
overwhelm receiver
reliability, flow control,
congestion control: throttle congestion control,
sender when network
overloaded timing, throughput
does not provide: timing, guarantee, security,
minimum throughput orconnection setup,
guarantee, security
connection-oriented: setup Q: why bother? Why is
required between client and there a UDP?
server processes
Application Layer 2-15
Internet apps: application, transport protocols
application underlying
application layer protocol transport protocol
e-mail SMTP [RFC 2821] TCP
remote terminal access Telnet [RFC 854] TCP
Web HTTP [RFC 2616] TCP
file transfer FTP [RFC 959] TCP
streaming multimedia HTTP (e.g., YouTube), TCP or UDP
RTP [RFC 1889]
Internet telephony SIP, RTP, proprietary
(e.g., Skype) TCP or UDP
Application Layer 2-16
Securing TCP
TCP & UDP SSL is at app layer
no encryption Apps use SSL
cleartext passwds sent libraries, which “ talk”
into socket traverse to TCP
Internet in cleartext SSL socket API
SSL cleartext passwds sent
provides encrypted into socket traverse
TCP connection Internet encrypted
data integrity See Chapter 7
end-point
authentication
Application Layer 2-17
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-18
Web and HTTP
First, a review…
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, e.g.,
www.someschool.edu/someDept/pic.gif
host name path name
Application Layer 2-19
HTTP overview
HTTP: hypertext transfer
protocol HT
Web’s application layer TP
req
ues
protocol PC running HT t
Firefox browser TPr
client/server model esp
ons
client: browser that e
requests, receives, t
(using HTTP protocol) u es
req server
and “ displays” Web T P n se
HT s po running
objects TP
re Apache Web
T
server: Web server H server
sends (using HTTP
protocol) objects in iphone running
response to requests Safari browser
Application Layer 2-20
HTTP overview (continued)
uses TCP: HTTP is “stateless”
client initiates TCP server maintains no
connection (creates socket) information about
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 be
messages) exchanged maintained
between browser (HTTP if server/client crashes, their
client) and Web server views of “ state” may be
(HTTP server) inconsistent, must be
TCP connection closed reconciled
Application Layer 2-21
HTTP connections
non-persistent HTTP persistent HTTP
at most one object sent multiple objects can
over TCP connection be sent over single
connection then TCP connection
closed between client, server
downloading multiple
objects required
multiple connections
Application Layer 2-22
Non-persistent HTTP
suppose user enters URL: (contains text,
www.someSchool.edu/someDepartment/home.index references to 10
jpeg images)
1a. HTTP client initiates TCP
connection to HTTP server
(process) at 1b. HTTP server at host
www.someSchool.edu on port 80 www.someSchool.edu waiting
for TCP connection at port 80.
“ accepts” connection, notifying
2. HTTP client sends HTTP request message client
(containing URL) into TCP connection
socket. Message indicates that client wants
object someDepartment/home.index 3. HTTP server receives request
message, forms response
message containing requested
object, and sends message into
its socket
time
Application Layer 2-23
Non-persistent HTTP (cont.)
4. HTTP server closes TCP
connection.
5. HTTP client receives response
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
Application Layer 2-24
Non-persistent HTTP: response time
RTT (definition): time for a
small packet to travel from
client to server and back
HTTP response time: initiate TCP
one RTT to initiate TCP connection
connection RTT
one RTT for HTTP request request
file
and first few bytes of HTTP time to
response to return RTT transmit
file
file transmission time
file
non-persistent HTTP received
response time =
2RTT+ file transmission time time
time
Application Layer 2-25
Persistent HTTP
non-persistent HTTP persistent HTTP:
issues: server leaves connection
requires 2 RTTs per object open after sending
OS overhead for each TCP response
connection subsequent HTTP
browsers often open messages between same
parallel TCP connections to client/server sent over
fetch referenced objects open connection
client sends requests as
soon as it encounters a
referenced object
as little as one RTT for all
the referenced objects
Application Layer 2-26
User-server state: cookies
example:
many Web sites use cookies Susan always access
four components: Internet from PC
1) cookie header line of visits specific e-commerce
HTTP response site for first time
message when initial HTTP requests
2) cookie header line in arrives at site, site creates:
next HTTP request unique ID
message entry in backend
3) cookie file kept on database for ID
user’s host, managed
by user’s browser
4) back-end database at
Web site
Application Layer 2-27
Cookies: keeping “ state” (cont.)
client server
ebay 8734
usual http request msg Amazon server
cookie file creates ID
usual http response
1678 for user create backend
ebay 8734
set-cookie: 1678 entry database
amazon 1678
usual http request msg
cookie: 1678 cookie- access
specific
usual http response msg action
one week later:
access
ebay 8734 usual http request msg
amazon 1678 cookie: 1678 cookie-
specific
usual http response msg action
Application Layer 2-28
Cookies (continued)
aside
what cookies can be used cookies and privacy:
for: cookies permit sites to
authorization learn a lot about you
shopping carts you may supply name and
recommendations
e-mail to sites
user session state (Web e-
mail)
how to keep “state”:
protocol endpoints: maintain state at
sender/receiver over multiple transactions
cookies: http messages carry state
Application Layer 2-29
Web caches (proxy server)
goal: satisfy client request without involving origin server
user sets browser: Web
accesses via cache
browser sends all HTTP proxy
HT
requests to cache TP
req server u est
HT ues P req
object in cache: cache client TP
res
t H TT po n se
origin
pon res
returns object se HT
T P server
t
else cache requests ues
req e
object from origin TT P o ns
p
H res
server, then returns HT TP
object to client
client origin
server
Application Layer 2-30
More about Web caching
cache acts as both why Web caching?
client and server reduce response time for
server for original client request
requesting client
client to origin server reduce traffic on an
typically cache is institution’s access link
installed by ISP Internet dense with
(university, company, caches: enables “ poor”
residential ISP) content providers to
effectively deliver
content (so too does P2P
file sharing)
Application Layer 2-31
Caching example:
assumptions:
avg object size: 100K bits origin
avg request rate from browsers to servers
origin servers:15/sec public
avg data rate to browsers: 1.50 Mbps Internet
RTT from institutional router to any
origin server: 2 sec
access link rate: 1.54 Mbps 1.54 Mbps
access link
consequences:
LAN utilization: 15% problem! institutional
network
access link utilization = 99% 1 Gbps LAN
total delay = Internet delay + access
delay + LAN delay
= 2 sec + minutes + usecs
Application Layer 2-32
Caching example: fatter access link
assumptions:
avg object size: 100K bits origin
avg request rate from browsers to servers
origin servers:15/sec public
avg data rate to browsers: 1.50 Mbps Internet
RTT from institutional router to any
origin server: 2 sec
access link rate: 1.54 Mbps
154 1.54 Mbps
154 Mbps
access link
consequences: Mbps
LAN utilization: 15% institutional
network
9.9%
access link utilization = 99% 1 Gbps LAN
total delay = Internet delay + access
delay + LAN delay
= 2 sec + minutes + usecs
msecs
Cost: increased access link speed (not cheap!)
Application Layer 2-33
Caching example: install local cache
assumptions:
avg object size: 100K bits origin
avg request rate from browsers to servers
origin servers:15/sec public
avg data rate to browsers: 1.50 Mbps Internet
RTT from institutional router to any
origin server: 2 sec
access link rate: 1.54 Mbps 1.54 Mbps
access link
consequences:
LAN utilization: 15% institutional
network
access link utilization?= 100% 1 Gbps LAN
total delay ?= Internet delay + access
delay + LAN delay local web
How to compute link cache
= 2 sec + minutes + usecs
utilization, delay?
Cost: web cache (cheap!)
Application Layer 2-34
Caching example: install local cache
Calculating access link
utilization, delay with cache:
suppose
origin
cache hit rate is 0.4 servers
40% requests satisfied at cache, 60% public
requests satisfied at origin Internet
access link utilization:
60% of requests use access link
data rate to browsers over access link = 1.54 Mbps
0.6*1.50 Mbps = .9 Mbps access link
utilization = 0.9/1.54 = .58 institutional
total delay network
= 0.6 * (delay from origin servers) +0.4 * (delay when 1 Gbps LAN
satisfied at cache)
= 0.6 (2.01) + 0.4 (~msecs) local web
= ~ 1.2 secs
less than with 154 Mbps link (and cheaper too!)
cache
Application Layer 2-35
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-36
FTP: the file transfer protocol
file transfer
FTP FTP FTP
user client server
interface
user
at host remote file
local file system
system
transfer file to/from remote host
client/server model
client: side that initiates transfer (either to/from remote)
server: remote host
ftp: RFC 959
ftp server: port 21
Application Layer 2-37
FTP: separate control, data connections
TCP control connection,
FTP client contacts FTP server server port 21
at port 21, using TCP
client authorized over control TCP data connection,
connection FTP server port 20 FTP
client server
client browses remote
directory, sends commands
over control connection server opens another TCP
data connection to transfer
when server receives file another file
transfer command, server
opens 2nd TCP data connection control connection: “out of
(for file) to client band”
after transferring one file, FTP server maintains “ state
server closes data connection ” : current directory, earlier
authentication
Application Layer 2-38
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-39
Electronic mail outgoing
message queue
user mailbox
Three major components: user
agent
user agents
mail servers mail user
server agent
simple mail transfer
protocol: SMTP SMTP mail user
server agent
User Agent SMTP
a.k.a. “ mail reader” SMTP user
agent
composing, editing, reading mail
mail messages server
user
e.g., Outlook, Thunderbird, agent
iPhone mail client user
outgoing, incoming agent
messages stored on server
Application Layer 2-40
Electronic mail: mail servers
mail servers: user
agent
mailbox contains incoming
messages for user mail user
server agent
message queue of outgoing
(to be sent) mail messages SMTP mail user
SMTP protocol between server agent
mail servers to send email SMTP
messages user
client: sending mail SMTP agent
mail
server server
user
“ server” : receiving mail agent
server
user
agent
Application Layer 2-41
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
Application Layer 2-42
Scenario: Alice sends message to Bob
1) Alice uses UA to compose 4) SMTP client sends Alice’s
message “ to” message over the TCP
[email protected] connection
2) Alice’s UA sends message to 5) Bob’s mail server places the
her mail server; message message in Bob’s mailbox
placed in message queue 6) Bob invokes his user agent to
3) client side of SMTP opens read message
TCP connection with Bob’s
mail server
1 user mail user
mail agent
agent server server
2 3 6
4
5
Alice’s mail server Bob’s mail server
Application Layer 2-43
Mail access protocols
user
mail user
SMTP SMTP access
agent agent
protocol
(e.g., POP,
IMAP)
sender’s mail receiver’s mail
server server
SMTP: delivery/storage to receiver’s server
mail access protocol: retrieval from server
POP: Post Office Protocol [RFC 1939]: authorization,
download
IMAP: Internet Mail Access Protocol [RFC 1730]: more
features, including manipulation of stored msgs on server
HTTP: gmail, Hotmail, Yahoo! Mail, etc.
Application Layer 2-44
POP3 and IMAP
more about POP3 IMAP
previous example uses keeps all messages in one
POP3 “ download and place: at server
delete” mode allows user to organize
Bob cannot re-read e- messages in folders
mail if he changes keeps user state across
client sessions:
POP3 “ download-and- names of folders and
keep” : copies of messages mappings between
on different clients message IDs and folder
POP3 is stateless across name
sessions
Application Layer 2-45
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-46
DNS: domain name system
people: many identifiers: Domain Name System:
SSN, name, passport # distributed database
Internet hosts, routers: implemented in hierarchy of
IP address (32 bit) - many name servers
used for addressing application-layer protocol:
datagrams hosts, name servers
“ name” , e.g., communicate to resolve
www.yahoo.com - names (address/name
used by humans translation)
note: core Internet function,
Q: how to map between IP
implemented as application-
address and name, and
layer protocol
vice versa ?
complexity at network’s
“ edge”
Application Layer 2-47
DNS: services, structure
DNS services why not centralize DNS?
hostname to IP address single point of failure
translation traffic volume
host aliasing distant centralized database
canonical, alias names maintenance
mail server aliasing
load distribution A: doesn’t scale!
replicated Web
servers: many IP
addresses correspond
to one name
Application Layer 2-48
DNS: a distributed, hierarchical database
Root DNS Servers
… …
com DNS servers org DNS servers edu DNS servers
pbs.org poly.edu umass.edu
yahoo.com amazon.com
DNS servers DNS serversDNS servers
DNS servers DNS servers
client wants IP for www.amazon.com; 1st approx:
client queries 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
Application Layer 2-49
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
c. Cogent, Herndon, VA (5 other sites)
d. U Maryland College Park, MD k. RIPE London (17 other sites)
h. ARL Aberdeen, MD
j. Verisign, Dulles VA (69 other sites ) i. Netnod, Stockholm (37 other sites)
m. WIDE Tokyo
e. NASA Mt View, CA (5 other sites)
f. Internet Software C.
Palo Alto, CA (and 48 other sites)
a. Verisign, Los Angeles CA 13 root name
(5 other sites)
b. USC-ISI Marina del Rey, CA
“servers” worldwide
l. ICANN Los Angeles, CA
(41 other sites)
g. US DoD Columbus,
OH (5 other sites)
Application Layer 2-50
TLD, authoritative servers
top-level domain (TLD) servers:
responsible for com, org, net, edu, aero, jobs, museums,
and all top-level country domains, e.g.: uk, fr, ca, jp
Network Solutions maintains servers for .com TLD
Educause for .edu TLD
authoritative DNS servers:
organization’s own DNS server(s), providing authoritative
hostname to IP mappings for organization’s named hosts
can be maintained by organization or service provider
Application Layer 2-51
Local DNS 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
has local cache of recent name-to-address translation
pairs (but may be out of date!)
acts as proxy, forwards query into hierarchy
Application Layer 2-52
DNS name root DNS server
resolution example
2
host at cis.poly.edu 3
TLD DNS server
wants IP address for 4
gaia.cs.umass.edu
5
local DNS server
iterated query: dns.poly.edu
contacted server replies 7 6
1 8
with name of server to
contact
authoritative DNS server
“ I don’t know this dns.cs.umass.edu
name, but ask this requesting host
cis.poly.edu
server”
gaia.cs.umass.edu
Application Layer 2-53
DNS name root DNS server
resolution example
2 3
recursive query: 7
6
puts burden of name TLD DNS
resolution on contacted server
name server
local DNS server
heavy load at upper dns.poly.edu 5 4
levels of hierarchy?
1 8
authoritative DNS server
dns.cs.umass.edu
requesting host
cis.poly.edu
gaia.cs.umass.edu
Application Layer 2-54
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-55
Pure P2P architecture
no always-on server
arbitrary end systems
directly communicate
peers are intermittently
connected and change IP
addresses
examples:
file distribution
(BitTorrent)
Streaming (KanKan)
VoIP (Skype)
Application Layer 2-56
Chapter 2: outline
2.1 principles of network 2.6 P2P applications
applications 2.7 socket programming
app architectures with UDP and TCP
app requirements
2.2 Web and HTTP
2.3 FTP
2.4 electronic mail
SMTP, POP3, IMAP
2.5 DNS
Application Layer 2-57
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
socket
applications
A host-local, application-
Client/server paradigm
Two types of transport service via socket
created, OS-controlled
API: interface (a “door”) into which
Reliable, byte stream-oriented (TCP) application process can both
Unreliable datagram (UDP) send and receive messages
to/from another application
process
API: Application Programming Interface
BSD: Berkeley Standard Distribution (Unix)
Applica
tion
Socket-programming using TCP
Socket: A door between application process and end-end-transport
protocol (UDP or TCP)
TCP service: Reliable transfer of bytes from one process to another
controlled by
controlled by application
application process process
developer
developer socket
socket controlled by
controlled by
TCP TCP
operating operating
with internet with system
system
buffers, buffers,
variable variable
host or
host or s
s
server server
Applica
tion
Socket programming with TCP
Client must contact server When contacted by client, server
Server process must first TCP creates new socket for server
be running process to communicate with client
Server must have created Allows server to talk with
socket (door) that multiple clients
welcomes client’s contact Source port numbers used to
Client contacts server by: distinguish clients
Creating client-local TCP
socket
Specifying IP address, port
number of server process
When client creates socket:
client TCP establishes Application viewpoint
connection to server TCP
TCP provides reliable, in-order
transfer of bytes (“pipe”) between
client and server
Applica
tion
Socket programming with TCP
keyboar monito
Example Client-Server App: d r
1) Client reads line from standard input input
strea
(inFromUser stream), sends to
server via socket (outToServer Process m
Client
stream) process
2) Server reads line from socket
3) Server converts line to uppercase, output input
sends back to client strea
m
strea
m
4) Client reads, prints client
clientSocket
modified line from socket TCP TC
P
socke
(inFromServer stream) socket t
to from
network network
Applica
tion
Client/server socket interaction: TCP
Server (running on Client
hostid)
create socket,
port=x, for incoming
request:
welcomeSocket =
ServerSocket()
wait for incoming
TCP create socket,
connection request connection connect to hostid, port=x
clientSocket =
connectionSocket = setup Socket()
welcomeSocket.accept()
send request using
read request from clientSocket
connectionSocket
write reply to
connectionSocket
read reply from
clientSocket
close
connectionSocket close
clientSocket
Applica
tion
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
{
String clientSentence; String capitalizedSentence;
Creat
welcominge ServerSocket welcomeSocket = new ServerSocket(6789);
socket
at port 6789 while(true) {
Wait, on Socket connectionSocket = welcomeSocket.accept();
welcoming
BufferedReader inFromClient = new BufferedReader (new
socketCreate
for InputStreamReader(connectionSocket.getInputStream()));
contact
input stream,
by client
attached
to socket
Applica
tion
Example: Java server (TCP), cont
Create
output stream, DataOutputStream outToClient =
attached new DataOutputStream(connectionSocket.getOutputStream());
to socket
Read in
line from clientSentence =
socket inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase()
Write out + '\n';
outToClient.writeBytes(capitalizedSente
line
} nce);
to socket }
} End of while loop, loop
back and wait for
another client
connection
Applica
tion
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
BufferedReader inFromUser =
input stream
new BufferedReader(new
Create InputStreamReader(System.in));
client socket, Socket clientSocket = new Socket(“localhost",
connect to 6789);
DataOutputStream outToServer =
server new
Create DataOutputStream(clientSocket.getOutputStream());
output stream
attached to
socket
Applica
tion
Example: Java client (TCP), cont.
Cre BufferedReader inFromServer = new
ate input stream BufferedReader(new
attached to InputStreamReader(clientSocket.getInputStream
socket ()));
sentence =
Send line to inFromUser.readLine();
server outToServer.writeBytes(sentence +
'\n');
Read line from modifiedSentence =
server inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Applica
tion
Chapter 2: Application layer
2.7 Socket programming
2.1 Principles of network with TCP
applications 2.8 Socket programming
2.2 Web and HTTP with UDP
2.3 FTP
2.4 Electronic Mail
SMTP, POP3, IMAP
2.5 DNS
Applica
tion
Socket programming with UDP
UDP: no “connection” between
client and server
No handshaking
Sender explicitly attaches IP
address and port of destination application viewpoint
to each packet
Server must extract IP address, UDP provides unreliable
port of sender from received transfer of groups of bytes
packet (“datagrams”) between client
UDP: Transmitted data may be and server
received out of order, or lost
Applica
tion
Client/server socket interaction: UDP
Server (running on Client
hostid)
create socket, create socket,
port=x, for incoming clientSocket =
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
Applica
tion
Example: Java server (UDP)
import java.io.*; import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
Cre
ate datagram DatagramSocket serverSocket = new DatagramSocket(9876);
socket at port
9876 byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
Create space
DatagramPacket receivePacket =
for received new DatagramPacket(receiveData, receiveData.length);
datagram serverSocket.receive(receivePacket);
Receive
datagram
Applica
tion
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
DatagramPacket sendPacket =
datagram to new DatagramPacket(sendData, sendData.length, IPAddress, port);
send to client
Write
serverSocket.send(sendPacket);
out }
datagra }
m to }
socket End of while loop,
loop back and wait
for another
datagram
Applica
tion
Example: Java client (UDP)
keyboard monitor
input
stream
Client
Input:
process
receives
Output: sends
packet (UDP
packet (UDP received
sent “byte UDP UDP “byte
packet packe
stream”) t stream”)
clientSocket
client
UDPsocke UDP
socket
t from network
to network
Applica
tion
Example: Java client (UDP)
import java.io.*; import java.net.*;
class UDPClient {
public static void main(String args[]) throws Exception
{
Crea
BufferedReader inFromUser =
te input new BufferedReader(new InputStreamReader(System.in));
stream
DatagramSocket clientSocket = new DatagramSocket();
Crea
te clientTransl InetAddress IPAddress = InetAddress.getByName(“localhost");
atesocket
hostname to byte[] sendData = new byte[1024];
IP address using byte[] receiveData = new byte[1024];
DNS
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
Applica
tion
Example: Java client (UDP),
cont.
Create datagram
with DatagramPacket sendPacket =
data-to-send, new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
length, IP addr,
Send clientSocket.send(sendPacket);
port datagram
DatagramPacket receivePacket =
to server new DatagramPacket(receiveData, receiveData.length);
Read
clientSocket.receive(receivePacket);
datagram
from String modifiedSentence =
server new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Applica
tion