Chapter 2: Application Layer - PowerPoint PPT Presentation

About This Presentation
Title:

Chapter 2: Application Layer

Description:

Keith updated in July 2002. Chapter 2: Application Layer Last Update: Oct 18, 2011 – PowerPoint PPT presentation

Number of Views:114
Avg rating:3.0/5.0
Slides: 117
Provided by: JimKurosea354
Category:

less

Transcript and Presenter's Notes

Title: Chapter 2: Application Layer


1
Chapter 2 Application Layer
  • Last Update Oct 18, 2011

2
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

3
Some network apps
  • E-mail
  • Web
  • Instant messaging
  • Remote login
  • P2P file sharing
  • Multi-user network games
  • Streaming stored video clips
  • Internet telephone
  • Real-time video conference
  • Massive parallel computing

4
Creating a network app
  • Write programs that
  • run on different end systems and
  • communicate over a network.
  • e.g., Web Web server software communicates with
    browser software
  • No software written for devices in network core
  • Network core devices do not function at app layer
  • This design allows for rapid app development

5
Application architectures
  • Client-server
  • Peer-to-peer (P2P)
  • Hybrid of client-server and P2P

6
Client-server archicture
  • 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

7
Pure P2P architecture
  • no always on server
  • arbitrary end systems directly communicate
  • peers are intermittently connected and change IP
    addresses
  • example Gnutella
  • Highly scalable
  • But difficult to manage

8
Hybrid of client-server and P2P
  • Skype
  • voice-over-IP P2P application
  • centralized server finding address of remote
    party
  • client-client connection direct (not through
    server)
  • 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 friends

9
Network applications some jargon
  • Process program running within a host.
  • within same host, two processes communicate using
    interprocess communication (defined by OS).
  • processes running in different hosts communicate
    with an application-layer protocol
  • user agent interfaces with user above and
    network below.
  • implements user interface application-level
    protocol
  • Web browser
  • E-mail mail reader
  • streaming audio/video media player

10
Applications and application-layer protocols
  • Application communicating, distributed processes
  • e.g., e-mail, Web, P2P file sharing, instant
    messaging
  • running in end systems (hosts)
  • exchange messages to implement application
  • Application-layer protocols
  • one piece of an app
  • define messages exchanged by apps and actions
    taken
  • use communication services provided by lower
    layer protocols (TCP, UDP)

11
App-layer protocol defines
  • Public-domain protocols
  • defined in RFCs
  • allows for interoperability
  • eg, HTTP, SMTP
  • Proprietary protocols
  • eg, KaZaA, Skype
  • Types of messages exchanged, eg, request
    response messages
  • Syntax of message types what fields in messages
    how fields are delineated
  • Semantics of the fields, ie, meaning of
    information in fields
  • Rules for when and how processes send respond
    to messages

12
Processes communicating across network
  • process sends/receives messages to/from its
    socket
  • socket analogous to door
  • sending process shoves message out door
  • sending process asssumes transport infrastructure
    on other side of door which brings message to
    socket at receiving process

controlled by app developer
Internet
controlled by OS
13
Addressing processes
  • For a process to receive messages, it must have
    an identifier
  • Every host has a unique 32-bit IP address
  • Q does the IP address of the host on which the
    process runs suffice for identifying the process?
  • Answer No, many processes can be running on same
    host
  • Identifier includes both the IP address and port
    numbers associated with the process on the host.
  • Example port numbers
  • HTTP server 80
  • Mail server 25

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

15
Transport service requirements of common apps
Time Sensitive no no no yes, 100s msec yes,
few secs yes, 100s msec yes and no
Application file transfer e-mail Web
documents real-time audio/video stored
audio/video interactive games instant messaging
Bandwidth elastic elastic elastic audio
5kbps-1Mbps video10kbps-5Mbps same as above few
kbps up elastic
Data loss no loss no loss no loss loss-tolerant
loss-tolerant loss-tolerant no loss
16
Internet transport protocols services
  • UDP service
  • unreliable data transfer between sending and
    receiving process
  • does not provide connection setup, reliability,
    flow control, congestion control, timing, or
    bandwidth guarantee
  • Q why bother? Why is there a UDP?
  • TCP service
  • connection-oriented setup required between
    client and server processes
  • reliable transport between sending and receiving
    process
  • flow control sender wont overwhelm receiver
  • congestion control throttle sender when network
    overloaded
  • does not providing timing, minimum bandwidth
    guarantees

17
Internet apps application, transport protocols
Application layer protocol SMTP RFC
2821 Telnet RFC 854 HTTP RFC 2616 FTP RFC
959 proprietary (e.g. RealNetworks) proprietary (
e.g., Dialpad)
Underlying transport protocol TCP TCP TCP TCP TCP
or UDP typically UDP
Application e-mail remote terminal access Web
file transfer streaming multimedia Internet
telephony
18
Web Application and HTTP Protocol
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

20
HTTP overview
  • HTTP hypertext transfer protocol
  • Webs 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

HTTP request
PC running Explorer
HTTP response
HTTP request
Server running Apache Web server
HTTP response
Mac running Navigator
21
HTTP overview (continued)
  • HTTP is stateless
  • server maintains no information about past client
    requests
  • Uses TCP
  • client initiates TCP connection (creates socket)
    to server, port 80
  • server accepts TCP connection from client
  • HTTP messages (application-layer protocol
    messages) exchanged between browser (HTTP client)
    and Web server (HTTP server)
  • TCP connection closed
  • 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

22
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

23
Nonpersistent HTTP
(contains text, references to 10 jpeg images)
  • Suppose user enters URL www.bilkent.edu.tr/someDep
    artment/
  • 1a. HTTP client initiates TCP connection to HTTP
    server (process) at www.bilkent.edu.tr on port 80

1b. HTTP server at host www.bilkent.edu.tr
waiting for TCP connection at port 80. accepts
connection, notifying client
2. HTTP client sends HTTP request message
(containing URL) into TCP connection socket.
Message indicates that client wants object
someDepartment/
3. HTTP server receives request message, forms
response message containing requested object, and
sends message into its socket
time
24
Nonpersistent 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
25
Response time modeling
  • Definition of RRT time to send a small packet to
    travel from client to server and back.
  • Response time
  • one RTT to initiate TCP connection
  • one RTT for HTTP request and first few bytes of
    HTTP response to return
  • file transmission time
  • total 2RTTtransmit time

26
Persistent HTTP
  • 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
  • Nonpersistent HTTP issues
  • requires 2 RTTs per object
  • OS must work and allocate host resources for each
    TCP connection
  • but 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 are sent over connection

27
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.bilkent.edu.tr User-agent
Mozilla/4.0 Connection close Accept-languagefr
(extra carriage return, line feed)
header lines
Carriage return, line feed indicates end of
message
28
HTTP request message general format
29
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

30
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?monkeysbanana
31
HTTP response message
status line (protocol status code status phrase)
HTTP/1.1 200 OK Connection close Date Thu, 06
Aug 1998 120015 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 ...
header lines
data, e.g., requested HTML file
32
HTTP response status codes
In first line in server-gtclient 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

33
Trying out HTTP (client side) for yourself
  • 1. Telnet to your favorite Web server

Opens TCP connection to port 80 (default HTTP
server port) at www.ee.bilkent.edu.tr. Anything
typed in sent to port 80 at www.ee.bilkent.edu.tr
telnet www.ee.bilkent.edu.tr 80
2. Type in a GET HTTP request
By typing this in (hit carriage return twice),
you send this minimal (but complete) GET request
to HTTP server
GET /ezhan/index.html HTTP/1.0
3. Look at response message sent by HTTP server!
34
User-server interaction authorization
  • Authorization control access to server content
  • authorization credentials typically name,
    password
  • stateless client must present authorization in
    each request
  • authorization header line in each request
  • if no authorization header, server refuses
    access, sends
  • WWW authenticate
  • header line in response

server
client
usual http request msg
401 authorization req. WWW authenticate
35
Cookies keeping state
  • Many major Web sites use cookies
  • Four components
  • 1) cookie header line in the HTTP response
    message
  • 2) cookie header line in HTTP request message
  • 3) cookie file kept on users host and managed by
    users browser
  • 4) back-end database at Web site
  • Example
  • Susan access Internet always from same PC
  • She visits a specific e-commerce site for first
    time
  • When initial HTTP requests arrives at site, site
    creates a unique ID and creates an entry in
    backend database for ID

36
Cookies keeping state (cont.)
server creates ID 1678 for user
entry in backend database
access
access
one week later
37
Cookies (continued)
  • Cookies and privacy
  • cookies permit sites to learn a lot about you
  • you may supply name and e-mail to sites
  • search engines use redirection cookies to
    learn yet more
  • advertising companies obtain info across sites
  • What cookies can bring
  • authorization
  • shopping carts
  • recommendations
  • user session state (Web e-mail)

38
Set-Cookie HTTP Response Header
  • Set-Cookie NAMEVALUE expiresDATE pathPATH
    domainDOMAIN_NAME secure
  • NAMEVALUE
  • sequence of characters excluding semi-colon,
    comma and white space (the only required field)
  • expiresDATE
  • Format Wdy, DD-Mon-YYYY HHMMSS GMT
  • domainDOMAIN_NAME
  • Browser performs tail matching searching
    through cookies file
  • Default domain is the host name of the server
    which generated the cookie response
  • pathPATH
  • the subset of URLs in a domain for which the
    cookie is valid
  • Secure if secure cookie will only be transmitted
    if the communications channel with the host is
    secure, e.g., HTTPS

39
Cookies File
  • Netscape keeps all cookies in a single file
    username/.netscape/cookies whereas IE keeps each
    cookie in separate files in the folder
    C\Documents and Settings\user\Cookies
  • Netscape HTTP Cookie File
  • http//www.netscape.com/newsref/std/cookie_spec.
    html
  • This is a generated file! Do not edit.
  • .netscape.com TRUE / FALSE
    1128258721 sampler 1097500321
  • .edge.ru4.com TRUE / FALSE
    2074142135 ru4.uid 2301274030263208642119
    17818738
  • .edge.ru4.com TRUE / FALSE
    1133246135 ru4.1188.gts 2
  • .netscape.com TRUE / FALSE
    1128065747 RWHAT set1128065747300
  • .nytimes.com TRUE / FALSE
    1159598159 RMID 833ff0b33a03433cdccf603e
  • .netscape.com TRUE / FALSE
    1128148560 adsNetPopup0 1128062159725
  • servedby.advertising.com TRUE /
    FALSE 1130654161 1812261973
    _433cdcd1,,69521476559_
  • .advertising.com TRUE / FALSE
    1285742161 ACID bb640011280621610000!
  • .bluestreak.com TRUE / FALSE
    1443407766 id 33167285258566120
    bb141A11twQw_"4totrKoAA adv
  • .mediaplex.com TRUE / FALSE
    1245628800 svid 80016269101
  • .nytdigital.com TRUE / FALSE
    1625726176 TID 0e0pcsb11jpn70
  • .nytdigital.com TRUE / FALSE
    1625726176 TData
  • .nytimes.com TRUE / FALSE
    1625726176 TID 0e0pcsb11jpn70
  • .nytimes.com TRUE / FALSE
    1625726176 TData

40
Cookies File Format
Domain Accessible by all hosts Path Secure Expiration (Unix time) Name Value
edge.ru4.com TRUE / FALSE 2074142135 ru4.uid 2301274
nytimes.com TRUE / FALSE 1625726176 TID 0e0pcsb11jpn70
Thu, 8 Jul 2021 063616 UTC
Sun, 23 Sep 2035 063535 UTC
41
Conditional GET client-side caching
server
client
  • Goal dont send object if client has up-to-date
    cached version
  • client specify date of cached copy in HTTP
    request
  • If-modified-since ltdategt
  • server response contains no object if cached
    copy is up-to-date
  • HTTP/1.0 304 Not Modified

HTTP request msg If-modified-since ltdategt
object not modified
HTTP request msg If-modified-since ltdategt
object modified
HTTP response HTTP/1.0 200 OK ltdatagt
42
File Transfer Application and FTP Protocol
43
FTP the file transfer protocol
file transfer
user at host
remote file 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

44
FTP separate control, data connections
  • FTP client contacts FTP server at port 21,
    specifying TCP as transport protocol
  • Client obtains authorization over control
    connection
  • Client browses remote directory by sending
    commands over control connection.
  • When server receives a command for a file
    transfer, the server opens a TCP data connection
    to client
  • After transferring one file, server closes
    connection.
  • Server opens a second TCP data connection to
    transfer another file.
  • Control connection out of band
  • FTP server maintains state current directory,
    earlier authentication

45
FTP commands, responses
  • Sample commands
  • sent as ASCII text over control channel
  • USER username
  • PASS password
  • LIST return list of file in current directory
  • RETR filename retrieves (gets) file
  • STOR filename stores (puts) file onto remote host
  • Sample return codes
  • status code and phrase (as in HTTP)
  • 331 Username OK, password required
  • 125 data connection already open transfer
    starting
  • 425 Cant open data connection
  • 452 Error writing file

46
Email Application and Email Protocols
47
Electronic Mail
  • Three major components
  • user agents
  • mail servers
  • simple mail transfer protocol SMTP
  • User Agent
  • a.k.a. mail reader
  • composing, editing, reading mail messages
  • e.g., Eudora, Outlook, elm, Netscape Messenger
  • outgoing, incoming messages stored on server

48
Electronic Mail mail servers
  • 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

49
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

50
Scenario Ayse sends message to Ali
  • 4) SMTP client sends Ayses message over the TCP
    connection
  • 5) Alis mail server places the message in Alis
    mailbox
  • 6) Ali invokes his user agent to read message
  • 1) Ayse uses UA to compose message and to
    ali_at_bilkent.edu.tr
  • 2) Ayses UA sends message to her mail server
    message placed in message queue
  • 3) Client side of SMTP opens TCP connection with
    Alis mail server

Ali
Ayse
1
2
6
3
4
5
51
SMTP interaction for yourself
  • telnet cs.bilkent.edu.tr 25
  • 220 gordion.cs.bilkent.edu.tr ESMTP Sendmail
    8.12.9/8.12.9
  • Wed, 3 Mar 2004 111752 0200 (EET)
  • HELO cs.bilkent.edu.tr
  • 250 gordion.cs.bilkent.edu.tr Hello
    nemrut.ee.bilkent.edu.
  • tr 139.179.12.28, pleased to meet you
  • MAIL FROM ltsomebody_at_somewhere.netgt
  • 250 2.1.0 ltsomebody_at_somewhere.netgt... Sender ok
  • RCPT TO ltezhan_at_ee.bilkent.edu.trgt
  • 250 2.1.5 ltezhan_at_ee.bilkent.edu.trgt...
    Recipient ok
  • DATA
  • 354 Enter mail, end with "." on a line by
    itself
  • hello
  • .
  • 250 2.0.0 Message accepted for delivery
  • QUIT
  • 221 2.0.0 gordion.cs.bilkent.edu.tr closing
    connection

52
SMTP final words
  • SMTP uses persistent connections
  • SMTP requires message (header body) to be in
    7-bit ASCII
  • SMTP server uses CRLF.CRLF to determine end of
    message
  • Comparison with HTTP
  • HTTP pull
  • SMTP push
  • both have ASCII command/response interaction,
    status codes
  • HTTP each object encapsulated in its own
    response msg
  • SMTP multiple objects sent in multipart msg

53
Mail access protocols
SMTP
access protocol
receivers mail server
  • SMTP delivery/storage to receivers server
  • Mail access protocol retrieval from server
  • POP Post Office Protocol RFC 1939
  • authorization (agent lt--gtserver) and download
  • IMAP Internet Mail Access Protocol RFC 1730
  • more features (more complex)
  • manipulation of stored msgs on server
  • HTTP Hotmail , Yahoo! Mail, etc.

54
Name Translation and DNS (domain name system)
Protocol
55
DNS Domain Name System
  • People many identifiers
  • SSN, name, passport
  • Internet hosts, routers
  • IP address (32 bit) - used for addressing
    datagrams
  • name, e.g., www.cs.bilkent.edu.tr - used by
    humans
  • Q map between IP addresses and name ?
  • Domain Name System
  • distributed database implemented in hierarchy of
    many name servers
  • application-layer protocol host, routers, name
    servers to communicate to resolve names
    (address/name translation)
  • note core Internet function, implemented as
    application-layer protocol
  • complexity at networks edge

56
DNS
  • Why not centralize DNS?
  • single point of failure
  • traffic volume
  • distant centralized database
  • maintenance
  • doesnt scale!
  • DNS services
  • Hostname to IP address translation
  • Host aliasing
  • Canonical and alias names
  • Mail server aliasing
  • Load distribution
  • Replicated Web servers set of IP addresses for
    one canonical name

57
Distributed, Hierarchical Database
  • 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

58
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

13 root name servers worldwide
59
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
  • Authoritative DNS servers organizations DNS
    servers, providing authoritative hostname to IP
    mappings for organizations servers (e.g., Web
    and mail).
  • Can be maintained by organization or service
    provider

60
Local Name Server
  • Does not strictly belong to hierarchy
  • Each ISP (residential ISP, company, university)
    has one.
  • Also called default name server
  • When a host makes a DNS query, query is sent to
    its local DNS server
  • Acts as a proxy, forwards query into hierarchy.

61
Example
root DNS server
  • Host at firat.bilkent.edu.tr wants IP address for
    gaia.cs.umass.edu

62
Recursive queries
  • recursive query
  • puts burden of name resolution on contacted name
    server
  • heavy load?
  • iterated query
  • contacted server replies with name of server to
    contact
  • I dont know this name, but ask this server

63
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.h
    tml

64
DNS records
  • DNS distributed db storing resource records (RR)
  • TypeA
  • name is hostname
  • value is IP address
  • TypeCNAME
  • name is alias name for some cannonical (the
    real) name
  • www.ibm.com is really
  • servereast.backup2.ibm.com
  • value is cannonical name
  • TypeNS
  • name is domain (e.g. foo.com)
  • value is IP address of authoritative name server
    for this domain
  • TypeMX
  • value is name of mailserver associated with name

65
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

66
DNS protocol, messages
Name, type fields for a query
RRs in reponse to query
records for authoritative servers
additional helpful info that may be used
67
Inserting records into DNS
  • Example just created startup Network Utopia
  • Register name networkuptopia.com 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
  • (networkutopia.com, dns1.networkutopia.com, NS)
  • (dns1.networkutopia.com, 212.212.212.1, A)
  • Put in authoritative server Type A record for
    www.networkutopia.com and Type MX record for
    mail.networkutopia.com

68
How do people connect to Web server?
com TLD DNS server
contains type A and NS RRs for Network Utopia
3 reply contains IP address for auth. name
server for Network Utopia (212.212.212.1)
2
authoritative name server for Network Utopia IP
212.212.212.1
4
local DNS server dns.bilkent.edu.tr
5 reply contains IP address for Web server for
Network Utopia (212.212.212.178)
1
6
Web server for Network Utopia IP 212.212.212.178
  • requesting host
  • firat.bilkent.edu.tr

7
TCP connection
69
Network Application Programming(Socket
Programming)
70
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 apps
  • client/server paradigm
  • two types of transport service via socket API
  • unreliable datagram
  • reliable, byte stream-oriented

71
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 application developer
controlled by application developer
controlled by operating system
controlled by operating system
internet
host or server
host or server
72
Socket programming with TCP
  • Client must contact server
  • server process must first be running
  • server must have created socket (door) that
    welcomes clients contact
  • Client contacts server by
  • creating client-local TCP socket
  • specifying IP address, port number of server
    process
  • When client creates socket client TCP
    establishes connection to server TCP
  • When contacted by client, server TCP creates new
    socket for server process to communicate with
    client
  • allows server to talk with multiple clients
  • source port numbers used to distinguish clients
    (more in Chap 3)

73
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, eg, keyboard or socket.
  • An output stream is attached to an output source,
    eg, monitor or socket.

74
Socket programming with TCP
  • Example client-server app
  • 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)

Client process
client TCP socket
75
Client/server socket interaction TCP
Server (running on hostid)
Client
76
Example Java client (TCP)
import java.io. import java.net. class
TCPClient public static void main(String
argv) throws Exception String
sentence String modifiedSentence
BufferedReader inFromUser new
BufferedReader(new InputStreamReader(System.in))
Socket clientSocket new
Socket("hostname", 6789)
DataOutputStream outToServer new
DataOutputStream(clientSocket.getOutputStream())

Create input stream
Create client socket, connect to server
Create output stream attached to socket
77
Example Java client (TCP), cont.
Create input stream attached to socket
BufferedReader inFromServer
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()))
sentence inFromUser.readLine()
outToServer.writeBytes(sentence '\n')
modifiedSentence inFromServer.readLine()
System.out.println("FROM SERVER "
modifiedSentence) clientSocket.close()

Send line to server
Read line from server
78
Example Java server (TCP)
import java.io. import java.net. class
TCPServer public static void main(String
argv) throws Exception String
clientSentence String capitalizedSentence
ServerSocket welcomeSocket new
ServerSocket(6789) while(true)
Socket connectionSocket
welcomeSocket.accept()
BufferedReader inFromClient new
BufferedReader(new
InputStreamReader(connectionSocket.getInputStream(
)))
Create welcoming socket at port 6789
Wait, on welcoming socket for contact by client
Create input stream, attached to socket
79
Example Java server (TCP), cont
DataOutputStream outToClient
new DataOutputStream(connectionSocket.get
OutputStream()) clientSentence
inFromClient.readLine()
capitalizedSentence clientSentence.toUpperCase()
'\n' outToClient.writeBytes(capit
alizedSentence)
Create output stream, attached to socket
Read in line from socket
Write out line to socket
End of while loop, loop back and wait for another
client connection
80
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
  • UDP transmitted data may be received out of
    order, or lost

81
Client/server socket interaction UDP
Server (running on hostid)
82
Example Java client (UDP)
Client process
Input receives packet (TCP received byte
stream)
Output sends packet (TCP sent byte stream)
client UDP socket
83
Example Java client (UDP)
import java.io. import java.net. class
UDPClient public static void main(String
args) throws Exception
BufferedReader inFromUser new
BufferedReader(new InputStreamReader(System.in))
DatagramSocket clientSocket new
DatagramSocket() InetAddress IPAddress
InetAddress.getByName("hostname")
byte sendData new byte1024 byte
receiveData new byte1024 String
sentence inFromUser.readLine() sendData
sentence.getBytes()
Create input stream
Create client socket
Translate hostname to IP address using DNS
84
Example Java client (UDP), cont.
Create datagram with data-to-send, length, IP
addr, port
DatagramPacket sendPacket new
DatagramPacket(sendData, sendData.length,
IPAddress, 9876) clientSocket.send(send
Packet) DatagramPacket receivePacket
new DatagramPacket(receiveData,
receiveData.length) clientSocket.receiv
e(receivePacket) String
modifiedSentence new
String(receivePacket.getData())
System.out.println("FROM SERVER"
modifiedSentence) clientSocket.close()

Send datagram to server
Read datagram from server
85
Example Java server (UDP)
import java.io. import java.net. class
UDPServer public static void main(String
args) throws Exception
DatagramSocket serverSocket new
DatagramSocket(9876) byte
receiveData new byte1024 byte
sendData new byte1024 while(true)
DatagramPacket
receivePacket new
DatagramPacket(receiveData, receiveData.length)
serverSocket.receive(receivePacket)
Create datagram socket at port 9876
Create space for received datagram
Receive datagram
86
Example Java server (UDP), cont
String sentence new
String(receivePacket.getData())
InetAddress IPAddress receivePacket.getAddress()
int port receivePacket.getPort()
String
capitalizedSentence sentence.toUpperCase()
sendData capitalizedSentence.getBytes()
DatagramPacket sendPacket
new DatagramPacket(sendData,
sendData.length, IPAddress,
port) serverSocket.send(s
endPacket)
Get IP addr port , of sender
Create datagram to send to client
Write out datagram to socket
End of while loop, loop back and wait for another
datagram
87
Socket programming references
  • Java-tutorials
  • All About Sockets (Sun tutorial),
    http//www.javaworld.com/javaworld/jw-12-1996/jw-1
    2-sockets.html
  • Socket Programming in Java a tutorial,
    http//www.javaworld.com/javaworld/jw-12-1996/jw-1
    2-sockets.html

88
Web Caching and Content Distribution
89
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
Proxy server
HTTP request
HTTP request
client
HTTP response
HTTP response
HTTP request
HTTP response
client
origin server
90
More about Web caching
  • Cache acts as both client and server
  • Cache can do up-to-date check using
    If-modified-since HTTP header
  • Issue should cache take risk and deliver cached
    object without checking?
  • Heuristics are used.
  • Typically cache is installed by ISP (university,
    company, residential ISP)
  • Why Web caching?
  • Reduce response time for client request.
  • Reduce traffic on an institutions access link.
  • Internet dense with caches enables poor content
    providers to effectively deliver content

91
Caching example (1)
origin servers
  • Assumptions
  • average object size 100,000 bits
  • avg. request rate from institutions browser to
    origin serves 15/sec
  • delay from institutional router to any origin
    server and back to router 2 sec
  • Consequences
  • utilization on LAN 15
  • utilization on access link 100
  • total delay Internet delay access delay
    LAN delay
  • 2 sec minutes (high util.) milliseconds

public Internet
1.5 Mbps access link
institutional network
10 Mbps LAN
institutional cache
92
Caching example (2)
origin servers
  • Possible solution
  • increase bandwidth of access link to, say, 10
    Mbps
  • Consequences
  • utilization on LAN 15
  • utilization on access link 15
  • Total delay Internet delay access delay
    LAN delay
  • 2 sec msecs msecs
  • often a costly upgrade

public Internet
10 Mbps access link
institutional network
10 Mbps LAN
institutional cache
93
Caching example (3)
origin servers
  • Install cache
  • suppose hit rate is .4
  • Consequence
  • 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)

public Internet
1.5 Mbps access link
institutional network
10 Mbps LAN
institutional cache
94
Content distribution networks (CDNs)
origin server in North America
  • The content providers are the CDN customers.
  • Content replication
  • CDN company installs hundreds of CDN servers
    throughout Internet
  • in lower-tier ISPs, close to users
  • CDN replicates its customers content in CDN
    servers. When provider updates content, CDN
    updates servers

CDN distribution node
CDN server in S. America
CDN server in Asia
CDN server in Europe
95
CDN example
  • CDN company
  • cdn.com
  • distributes gif files
  • uses its authoritative DNS server to route
    redirect requests
  • origin server
  • www.foo.com
  • distributes HTML
  • Replaces
  • http//www.foo.com/sports.ruth.gif
  • with
    http//www.cdn.com/www.foo.com/sports/ruth.gif

96
More about CDNs
  • routing requests
  • CDN creates a map, indicating distances from
    leaf ISPs and CDN nodes
  • when query arrives at authoritative DNS server
  • server determines ISP from which query
    originates
  • uses map to determine best CDN server
  • not just Web pages
  • streaming stored audio/video
  • streaming real-time audio/video
  • CDN nodes create application-layer overlay network

97
P2P Applications and Protocols
98
Pure P2P architecture
  • no always-on server
  • arbitrary end systems directly communicate
  • peers are intermittently connected and change IP
    addresses

2 Application Layer
98
99
File Distribution Server-Client vs P2P
  • Question How much time to distribute file from
    one server to N peers?

us server upload bandwidth
Server
ui peer i upload bandwidth
u2
d1
u1
d2
us
di peer i download bandwidth
File, size F
dN
Network (with abundant bandwidth)
uN
2 Application Layer
99
100
File distribution time server-client
Server
  • server sequentially sends N copies
  • NF/us time
  • client i takes F/di time to download

u2
F
d1
u1
d2
us
Network (with abundant bandwidth)
dN
uN
increases linearly in N (for large N)
2 Application Layer
100
101
File distribution time P2P
Server
  • server must send one copy F/us time
  • client i takes F/di time to download
  • NF bits must be downloaded (aggregate)

u2
F
d1
u1
d2
us
Network (with abundant bandwidth)
dN
uN
  • fastest possible upload rate us Sui

dP2P max F/us, F/mini di) , NF/(us Sui)
2 Application Layer
101
102
Server-client vs. P2P example
Client upload rate u, F/u 1 hour, us 10u,
dmin us
2 Application Layer
102
103
Searching for Information-Query flooding
Gnutella
  • fully distributed
  • no central server
  • public domain protocol
  • many Gnutella clients implementing protocol
  • overlay network graph
  • edge between peer X and Y if theres a TCP
    connection
  • all active peers and edges is overlay net
  • Edge is not a physical link
  • Given peer will typically be connected with lt 10
    overlay neighbors

104
Gnutella protocol
File transfer HTTP
  • Query messagesent over existing TCPconnections
  • peers forwardQuery message
  • QueryHit sent over reversepath

Scalability limited scopeflooding
105
Gnutella Peer joining
  • Joining peer X must find some other peer in
    Gnutella network use list of candidate peers
  • X sequentially attempts to make TCP with peers on
    list until connection setup with Y
  • X sends Ping message to Y Y forwards Ping
    message.
  • All peers receiving Ping message respond with
    Pong message
  • X receives many Pong messages. It can then setup
    additional TCP connections

106
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.
  • Group leader tracks the content in all its
    children.

107
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

108
Kazaa tricks
  • Limitations on simultaneous uploads
  • Request queuing
  • Incentive priorities
  • Parallel downloading

109
P2P Case Study BitTorrent
P2P file distribution
tracker tracks peers participating in torrent
torrent group of peers exchanging chunks of a
file
2 Application Layer
109
110
BitTorrent (1)
  • file divided into 256KB chunks.
  • peer joining torrent
  • has no chunks, but will accumulate them over time
  • registers with tracker to get list of peers,
    connects to subset of peers (neighbors)
  • while downloading, peer uploads chunks to other
    peers.
  • peers may come and go
  • once peer has entire file, it may (selfishly)
    leave or (altruistically) remain

2 Application Layer
110
111
BitTorrent (2)
  • Sending Chunks tit-for-tat
  • Alice sends chunks to four neighbors currently
    sending her chunks at the highest rate
  • re-evaluate top 4 every 10 secs
  • every 30 secs randomly select another peer,
    starts sending chunks
  • newly chosen peer may join top 4
  • optimistically unchoke
  • Pulling Chunks
  • at any given time, different peers have different
    subsets of file chunks
  • periodically, a peer (Alice) asks each neighbor
    for list of chunks that they have.
  • Alice sends requests for her missing chunks
  • rarest first

2 Application Layer
111
112
P2P Case study Skype
  • inherently P2P pairs of users communicate.
  • proprietary application-layer protocol (inferred
    via reverse engineering)
  • hierarchical overlay with SNs
  • Index maps usernames to IP addresses distributed
    over SNs

Supernode (SN)
2 Application Layer
112
113
Skype making a call
  • User starts Skype
  • SC registers with SN
  • list of bootstrap SNs

Skype login server
  • SC logs in (authenticate)
  • Call SC contacts SN with callee ID
  • SN contacts other SNs (unknown protocol, maybe
    flooding) to find addr of callee returns addr
    to SC
  • SC directly contacts callee

114
Peers as relays
  • Problem when both Alice and Bob are behind
    NATs.
  • NAT prevents an outside peer from initiating a
    call to insider peer
  • Solution
  • Using Alices and Bobs SNs, Relay is chosen
  • Each peer initiates session with relay.
  • Peers can now communicate through NATs via relay

2 Application Layer
114
115
Summary
116
Additional Study Material
Write a Comment
User Comments (0)
About PowerShow.com