2ECEg 4191 Chapter 2 - Application Layer

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 63

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
• DNS
• client-server
paradigm  creating network
• peer-to-peer applications
paradigm • socket API

Application Layer 2-1


2.1 Some network apps
 e-mail  voice over IP (e.g.,
 web Skype)
 text messaging  real-time video
 P2P file sharing conferencing
 social networking
 streaming stored video
(YouTube, Netflix)  search

Application Layer 2-2


Creating a network app application
transport
network
data link
physical

write programs that:


 run on (different) end systems
 communicate over network
 e.g., web server software
communicates with browser
software

no need to write software for


application
transport
network

network-core devices data link


physical
application
transport
network
 network-core devices do not data link
physical
run user applications
 applications on end systems
allows for rapid app
development, propagation
Application Layer 2-3
Application architectures
possible structure of applications:
 client-server
 peer-to-peer (P2P)

Application Layer 2-4


Client-server architecture
server:
 always-on host
 permanent IP address
 data centers for scaling

clients:
 communicate with server
 may be intermittently
client/server
connected
 may have dynamic IP
addresses
 do not communicate directly
with each other

Application Layer 2-5


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
 peers are irregularly connected
and change IP addresses
• Eg, Gnutella
How?
By leader election- store index

Application Layer 2-6


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-7


Sockets
 process sends/receives messages to/from its socket
 socket analogous to door
• sending process pushes 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-8


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 ju.edu.et web server:
can be running on same • IP address: 213.55.92.84
host • port number: 80

Application Layer 2-9


Requirement for message transport
data integrity throughput
 some apps (e.g., file transfer,  some apps (e.g., multimedia)
web transactions) require require minimum amount of
100% reliable data transfer throughput to be “ effective”
 other apps (“ elastic apps” )
 other apps (e.g., audio) can
make use of whatever
tolerate some loss
throughput they get
timing
 some apps (e.g., Internet
telephony, interactive security
games) require low delay  encryption, data integrity, …
to be “ effective”

Application Layer 2-10


Transport service requirements: common apps

application data loss bitrate 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-11


Internet transport protocols services
TCP service: UDP service:
 reliable transport between  unreliable data transfer
sending and receiving process between sending and
 flow control: sender won’t receiving process
overwhelm receiver  does not provide:
 congestion control: throttle reliability, flow control,
sender when network congestion control,
overloaded timing, throughput
 does not provide: timing, guarantee, security, or
minimum throughput connection setup,
guarantee, security
 connection-oriented: setup
required between client and Q: why bother? Why is
server processes there a UDP?

Application Layer 2-12


2.2 Web and HTTP
2.2.1 HTTP
 web page consists of objects
 object can be HTML file, JPEG image, audio file,

 each object is addressable by a URL, e.g.,

www.ju.edu.et/jit/pic.gif
host name path name

Application Layer 2-13


HTTP overview
HTTP: hypertext transfer
protocol HT
 Web’s application layer TP
req
ues
protocol PC running HT t
Firefox browser TP
 client/server model res
pon
se
• client: browser that
requests, receives, t
(using HTTP protocol) u es
req server
and “ displays” Web T P n se
HT s po running
objects TP
r e Apache Web
T
• server: Web server H server
sends (using HTTP
protocol) objects in iPhone running
response to requests Safari browser

Application Layer 2-14


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
 HTTP messages
(application-layer protocol
messages) exchanged
between browser (HTTP
client) and Web server
(HTTP server)
 TCP connection closed

Application Layer 2-15


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-16


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
client
2. HTTP client sends HTTP request message
(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-17
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-18


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
and first few bytes of HTTP file
time to
response to return RTT transmit
 file transmission time file
file
 non-persistent HTTP response received
time =
2RTT+ file transmission time time
time

Application Layer 2-19


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-20


2.2.2 User-server state: cookies
example:
Many Web sites use
 Yohanes always access
cookies
Internet from PC
 visits specific sport site
 cookie file kept on for first time
user’s host, managed  when initial HTTP
by user’s browser. requests arrives at site,
 back-end database at site creates:
Web site • unique ID
• entry in backend
database for ID

Application Layer 2-21


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-22
Cookies (continued)
aside
what cookies can be used cookies and privacy:
for:
  cookies permit sites to
authorization
 learn a lot about you
shopping carts
 recommendations  you may supply name and
 user session state (Web e- e-mail to sites
mail)

Application Layer 2-23


Chapter 2 – Application Layer
Lecture 02

Lecture Outline:-
• Web Caches

• DNS

Application Layer 2-24


2.2.3 Web caches (proxy server)
Goal: satisfy client request without involving origin server

 Web accesses via cache


 browser sends all HTTP
proxy
requests to cache HT
TP ue st
req server req
• object in cache: cache HT
client TP
ues
t H TT P
p on se
origin
res res
returns object pon
se TP server
HT
• else cache requests u est
req e
object from origin TT P
p o ns
H res
server, then returns TTP
H
object to client
client origin
server

Application Layer 2-25


More about Web caching
 cache acts as both why Web caching?
client and server  reduce response time for
• server for requesting client client request
• client to origin server
 reduce traffic on an
 typically cache is
institution’s access link
installed by ISP
(university, company,
residential ISP)

Application Layer 2-26


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-27


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-28
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-29
Caching example: install local cache
Calculating access link utilization,
delay with cache:
 suppose cache hit rate is 0.4 origin
• 40% requests satisfied at cache, 60% servers
requests satisfied at origin public
Internet

 access link utilization:


 60% of requests use access link
 data rate to browsers over access link 1.54 Mbps
access link
= 0.6*1.50 Mbps = .9 Mbps
 utilization = 0.9/1.54 = .58 institutional
network
1 Gbps LAN
 total delay
 = 0.6 * (delay from origin servers) +0.4 local web
* (delay when satisfied at cache) cache
 = 0.6 (2.01) + 0.4 (~msecs) = ~ 1.2 secs
 less than with 154 Mbps link (and
cheaper too!)
Application Layer 2-30
2.3 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 ?

Application Layer 2-31


DNS Features:
 Data is maintained locally, but retrievable globally

• No single computer has all DNS data

 Remote DNS data is locally cachable to improve performance

 DNS protocols can use either UDP or TCP

• If UDP, DNS protocol handles retransmission, sequencing, etc.

 Database can be updated dynamically


• Add/delete/modify of any record

 Modification of the master database triggers replication


• Only master can be dynamically updated
Concept: Domains
 Domains are “namespaces”
 Everything below .com is in the com domain.
 Everything below ripe.net is in the ripe.net
domain and in the net domain. •
com domain
net edu com •
• •
ripe.net domain google


ripe isi sun tislabs
moon •
net domain www disi
ftp
• www
ws2 ws1
Jump to first
page
Concept: Zones and Delegations
 Zones are “administrative spaces”
 Zone administrators are responsible for
portion of a domain’s name space

Authority is delegated from a parent and to a
child net zone

ne ed co
net domain • • m

t u google
ripe.net zone •
rip is sun tislab
e i moons •
ww dis
disi.ripe.net zone ww

w ft i
p ws ws w
Jump to first
page
DNS: services, structure
DNS services
 hostname to IP address
translation
 host aliasing why not centralize DNS?
• Example:
• single point of failure
• www.yahoo.com
• traffic volume, millions of
• tokiyo.yahoo.com mail, http…requests
(set of IP addresses for one
• distant centralized database
canonical name)
 load distribution • maintenance
• replicated Web servers:
many IP addresses  A: Therefore, a centralized
correspond to one name database approach
doesn’t scale!

Application Layer 2-35


Distributed, Hierarchical Database
Root DNS Servers

Top-level domain servers

com DNS servers org DNS servers edu DNS servers


Intermediate DNS servers
Authoritative DNS serverspoly.edu umass.edu
yahoo.com amazon.com pbs.org
DNS servers DNS servers DNS servers
DNS servers DNS servers

Each ISP also has a Local DNS server (default name server)

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

DNS query and reply messages are sent within UDP datagrams to port 53.
53
Application 2-36
DNS: Root name servers
 contacted by local name server that cannot resolve name
 root name server:
1. contacts authoritative name server if name mapping is not known
2. gets mapping
3. 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 k RIPE London (also 16 other locations)
h ARL Aberdeen, MD
j Verisign, ( 21 locations) i Autonomica, Stockholm (plus 28 other locations)

e NASA Mt View, CA
m WIDE Tokyo (also Seoul, Paris, SF)
f Internet Software C. Palo Alto, CA (and 36
other locations)

13 root name
servers worldwide
b USC-ISI Marina del Rey, CA
l ICANN Los Angeles, CA

Application 2-37
TLD and Authoritative Servers
Top-level domain (TLD) servers:
 responsible for com, org, net, edu, and all top-level
country domains, e.g.: uk, fr, ch, jp, nz
 Network Solutions maintains servers for com TLD
 Educause 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

Application 2-38
Local Name Server
 does not strictly belong to hierarchy
 each ISP (residential ISP, company, university)
has one
 also called “default name server”
server
 when host makes DNS query, query is sent to its
local DNS server
 acts as proxy, forwards query into hierarchy of DNS
servers

Application 2-39
DNS in action
 What happens when a user wants to view a
website (e.g. www.networkutopia.com)?

 Let’s trace the sequence of DNS server


interaction.

2: Application Layer 40
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
Authoritative DNS Server (primary)

1
Dns2.networkutopia.com
Authoritative DNS Server (secondary)

Requesting
host
Destination
Host

2: Application Layer 41
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

2
Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
Authoritative DNS Server (primary)

1
Dns2.networkutopia.com
Authoritative DNS Server (secondary)

Requesting
host
Destination
Host

2: Application Layer 42
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

2 3
Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
Authoritative DNS Server (primary)

1
Dns2.networkutopia.com
Authoritative DNS Server (secondary)

Requesting
host
Destination
Host

2: Application Layer 43
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3
Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
Authoritative DNS Server (primary)

1
Dns2.networkutopia.com
Authoritative DNS Server (secondary)

Requesting
host
Destination
Host

2: Application Layer 44
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3 5
Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
Authoritative DNS Server (primary)

1
Dns2.networkutopia.com
5. Resource Records Authoritative DNS Server (secondary)
(networkutopia.com, Dns1.networkutopia.com, NS)
Requesting
host
(Dns1.networkutopia.com, 212.212.212.1, A)
Destination
...etc. Host

2: Application Layer 45
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3 5
Dns1.networkutopia.com
Local DNS
Server IP: 212.212.212.1
6 Authoritative DNS Server (primary)

1
Dns2.networkutopia.com

6. What is the IP address Authoritative


of DNS Server (secondary)

www.networkutopia.com?
www.networkutopia.com
Requesting
host - give me a Type A Resource
Destination
Record Host

2: Application Layer 46
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3 5
Dns1.networkutopia.com
Local DNS
Server 6 IP: 212.212.212.1
Authoritative DNS Server (primary)
7
1
Dns2.networkutopia.com
Authoritative DNS Server (secondary)

Requesting
host
Destination
Host

7. Type A Resource Record:


(www.networkutopia.com, 212.212.71.4, 2:A)Application Layer 47
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3 5
Dns1.networkutopia.com
Local DNS
Server 6 IP: 212.212.212.1
Authoritative DNS Server (primary)
7
1 8 Dns2.networkutopia.com
Authoritative DNS Server (secondary)

8. IP address of www.networkutopia.com
Requesting
host
is 212.212.71.4
Destination
Host

2: Application Layer 48
DNS
i.e. Name Server responsible for COM
Root DNS
Server
Top-Level Domain
(TLD) DNS Server

4
2 3 5
Dns1.networkutopia.com
Local DNS
Server 6 IP: 212.212.212.1
Authoritative DNS Server (primary)
7
1 8 Dns2.networkutopia.com
Authoritative DNS Server (secondary)

9
Requesting
host
Destination networkutopia.com
Host IP: 212.212.71.4

9. TCP connection with www.networkutopia.com


(212.212.71.4), HTTP request 2: Application Layer 49
DNS name resolution root DNS server

2 3
7
6

Method 2. recursive query: TLD DNS


server
 puts burden of name resolution
on contacted name server local DNS server
dns.poly.edu 5 4
 heavy load at upper levels of
hierarchy? 1 8

authoritative DNS server


dns.cs.umass.edu
requesting host
cis.poly.edu

gaia.cs.umass.edu

Application Layer 2-50


DNS: caching, updating records
 once (any) name server learns mapping, it caches
mapping
• cache entries timeout (disappear) after some time (TTL)
(often set to 2 days)
• TLD servers typically cached in local name servers
• thus root name servers not often visited
 update/notify mechanisms proposed IETF standard
• RFC 2136

Application Layer 2-51


DNS records
DNS: distributed database storing resource records (RR)
RR format: (name, value, type, ttl)
type=A
 name is hostname, value is IP address. type=CNAME
DNS is authoritative for a hostname  name is alias name for some “ canonical” (the
 (relay1.bar.foo.com, 145.37.93.126, A) real) name
 www.ibm.com is really
type=NS servereast.backup2.ibm.com
DNS is not authoritative for a hostname  value is canonical name
 name is domain (e.g., ibm.com)  (ibm.com, relay1.bar.ibm.com, CNAME)
 value is name of an authoritative server name for this
domain.
• that knows how to obtain the IP addresses for hosts in the domain.
• (ibm.com, dns.ibm.com, NS)
DNS resource records
An “A” record supplies a host IP address
A “NS” record supplies name server for the
requested domain.
Application Layer 2-52
Inserting records into DNS
 example: new startup “ ethopia”

 register name ethiopia.com at DNS registrar


• provide names, IP addresses of authoritative name server

• registrar inserts two RRs into .com TLD server:


(ethopia.com, dns1.ethopia.com, NS)

(dns1.ethopia.com, 212.212.212.1, A)

Application Layer 2-53


2.4 Socket programming
(Further reading)
goal: learn how to build client/server applications that
communicate using sockets
socket: door between application process and end-end-
transport protocol

application application
socket controlled by
process process app developer

transport transport
network network controlled
link
by OS
link Internet
physical physical

Application Layer 2-54


Socket programming
Two socket types for two transport services:
• UDP: unreliable datagram
• TCP: reliable, byte stream-oriented

Application Example:
1. client reads a line of characters (data) from its
keyboard and sends data to server
2. server receives the data and converts characters to
uppercase
3. server sends modified data to client
4. client receives modified data and displays line on
its screen
Application Layer 2-55
Socket programming with UDP
UDP: no “ connection” between client & server
 no handshaking before sending data
 sender explicitly attaches IP destination address and
port # to each packet
 receiver extracts sender IP address and port# from
received packet
UDP: transmitted data may be lost or received
out-of-order
Application viewpoint:
 UDP provides unreliable transfer of groups of bytes (
“ datagrams” ) between client and server

Application Layer 2-56


Client/server socket interaction: UDP

server (running on serverIP) client


create socket:
create socket, port= x: clientSocket =
serverSocket = socket(AF_INET,SOCK_DGRAM)
socket(AF_INET,SOCK_DGRAM)
Create datagram with server IP and
port=x; send datagram via
read datagram from clientSocket
serverSocket

write reply to
serverSocket read datagram from
specifying clientSocket
client address,
port number close
clientSocket

Application 2-57
Example app: UDP client
Python UDPClient
include Python’s socket
library from socket import *
serverName = ‘hostname’
serverPort = 12000
create UDP socket for clientSocket = socket(AF_INET,
server
SOCK_DGRAM)
get user keyboard
input message = raw_input(’Input lowercase sentence:’)
Attach server name, port to
message; send into socket
clientSocket.sendto(message.encode(),
(serverName, serverPort))
read reply characters from
modifiedMessage, serverAddress =
socket into string
clientSocket.recvfrom(2048)
print out received string
and close socket
print modifiedMessage.decode()
clientSocket.close()
Application Layer 2-58
Example app: UDP server
Python UDPServer
from socket import *
serverPort = 12000
create UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM)
bind socket to local port
number 12000 serverSocket.bind(('', serverPort))
print (“The server is ready to receive”)
loop forever
while True:
Read from UDP socket into
message, getting client’s
message, clientAddress = serverSocket.recvfrom(2048)
address (client IP and port) modifiedMessage = message.decode().upper()
send upper case string serverSocket.sendto(modifiedMessage.encode(),
back to this client
clientAddress)

Application Layer 2-59


Socket programming with TCP
client must contact server  when contacted by client,
 server process must first be server TCP creates new socket
running for server process to
communicate with that
 server must have created particular client
socket (door) that welcomes
client’s contact • allows server to talk with
multiple clients
client contacts server by: • source port numbers used to
 Creating TCP socket, distinguish clients (more in
specifying IP address, port Chap 3)
number of server process
 when client creates socket: application viewpoint:
client TCP establishes TCP provides reliable, in-order
connection to server TCP byte-stream transfer (“ pipe” )
between client and server

Application Layer 2-60


Client/server socket interaction: TCP
server (running on hostid) client
create socket,
port=x, for incoming
request:
serverSocket = socket()

wait for incoming create socket,


connection request
TCP connect to hostid, port=x
connectionSocket = connection setup clientSocket = socket()
serverSocket.accept()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
clientSocket

Application Layer 2-61


Example app: TCP client
Python TCPClient
from socket import *
serverName = ’servername’
create TCP socket for serverPort = 12000
server, remote port 12000
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
sentence = raw_input(‘Input lowercase sentence:’)
No need to attach server
name, port clientSocket.send(sentence.encode())
modifiedSentence = clientSocket.recv(1024)
print (‘From Server:’, modifiedSentence.decode())
clientSocket.close()

Application Layer 2-62


Example app: TCP server
Python TCPServer
from socket import *
create TCP welcoming serverPort = 12000
socket serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind((‘’,serverPort))
server begins listening for
incoming TCP requests serverSocket.listen(1)
print ‘The server is ready to receive’
loop forever
while True:
server waits on accept()
for incoming requests, new
connectionSocket, addr = serverSocket.accept()
socket created on return

read bytes from socket (but


sentence = connectionSocket.recv(1024).decode()
not address as in UDP) capitalizedSentence = sentence.upper()
close connection to this connectionSocket.send(capitalizedSentence.
client (but not welcoming
socket) encode())
connectionSocket.close()
Application Layer 2-63

You might also like