Anda di halaman 1dari 18

Chapter 2: Application Layer Chapter2: Application layer

Our goals: ‰ learn about protocols


‰ Principles of network applications
‰ conceptual, by examining popular
implementation application-level ™ Architecture: client-server or P2P
aspects of network protocols ™ Services that an application needs
application protocols ™ HTTP ‰ important application-level protocols
™ transport-layer ™ FTP
™ FTP, SMTP, P2P, ……
service models ™ SMTP / POP3 / IMAP
DNS ‰ programming network applications
™ client-server
™

paradigm ‰ programming network ™ socket API

™ peer-to-peer
applications ‰ Web stuff
paradigm ™ socket API
™ HTTP, DNS, Web searching

Introduction 1-1 Introduction 1-2

Creating a network app application


transport
Application architectures
network
data link

write programs that physical

™ run on (different) end


ˆ Client-server
systems ˆ Peer-to-peer (P2P)
™ communicate over network
™ e.g., web server software
ˆ Hybrid of client-server and P2P
communicates with browser
software application

No need to write software


transport
network
data link
for network-core devices
application
physical
transport
network
™ Network-core devices do data link
physical
not run user applications
™ applications on end systems
allows for rapid app
development, propagation
Introduction 1-3 2: Application Layer 4

1
Client-server architecture Pure P2P architecture
server:
ˆ no always-on server
™ always-on host
ˆ arbitrary end systems
™ permanent IP address directly communicate peer-peer
™ server farms for ˆ peers are intermittently
scaling connected and change IP
clients: addresses
client/server ™ communicate with server
™ may be intermittently
connected
™ may have dynamic IP Highly scalable but
addresses difficult to manage
™ do not communicate
directly with each other
2: Application Layer 5 2: Application Layer 6

Hybrid of client-server and P2P Processes communicating


Skype Process: program running Client process: process
™ Internet telephony app within a host. that initiates
™ Finding address of remote party: centralized server(s) ˆ within same host, two
communication
™ Client-client connection is direct (not through server) processes communicate Server process: process
Instant messaging using inter-process that waits to be
™ Chatting between two users is P2P communication (defined contacted
™ Presence detection/location centralized: by OS).
• User registers its IP address with central server when it ˆ processes in different ˆ Note: applications with
comes online
hosts communicate by P2P architectures have
• User contacts central server to find IP addresses of
buddies
exchanging messages client processes &
server processes

2: Application Layer 7 2: Application Layer 8

2
Sockets Addressing processes
ˆ to receive messages, ˆ identifier includes both
process sends/receives
host or host or
ˆ server server process must have IP address and port
messages to/from its identifier numbers associated with
socket controlled by
ˆ host device has unique process on host.
app developer
ˆ socket analogous to door process process
32-bit IP address ˆ Example port numbers:
™ sending process shoves socket socket
ˆ Q: does IP address of ™ HTTP server: 80
message out door
host on which process Mail server: 25
TCP with TCP with
Internet ™
buffers,
sending process relies on buffers,
runs suffice for
™
transport infrastructure
variables variables ˆ to send HTTP message
on other side of door which identifying the to gaia.cs.umass.edu web
brings message to socket controlled process? server:
by OS
at receiving process ™ A: No, many ™ IP address: 128.119.245.12
ˆ API: (1) choice of transport protocol; (2) ability to fix processes can be ™ Port number: 80
a few parameters (lots more on this later) running on same host ˆ more shortly…
2: Application Layer 9 2: Application Layer 10

What transport service does an app need?


App-layer protocol defines
Data loss Throughput
ˆ Types of messages Public-domain protocols: ˆ some apps (e.g., audio) can ˆ some apps (e.g.,
exchanged, tolerate some loss multimedia) require
ˆ defined in RFCs
e.g., request, response ˆ other apps (e.g., file minimum amount of
™
ˆ allows for transfer, telnet) require
Message syntax: throughput to be
ˆ interoperability 100% reliable data “effective”
™ what fields in messages & ˆ e.g., HTTP, SMTP transfer
how fields are delineated ˆ other apps (“elastic apps”)
Proprietary protocols: Timing make use of whatever
ˆ Message semantics
ˆ e.g., skype ˆ some apps (e.g., throughput they get
™ meaning of information in
Internet telephony,
fields Security
interactive games)
ˆ Rules for when and how require low delay to be ˆ Encryption, data
processes send & “effective” integrity, …
respond to messages
2: Application Layer 11 2: Application Layer 12

3
Transport service requirements of common apps Internet transport protocols services

Application Data loss Bandwidth Time Sensitive TCP service: UDP service:
ˆ connection-oriented: setup ˆ unreliable data transfer
file transfer no loss elastic no required between client and between sending and
e-mail no loss elastic no server processes receiving process
Web documents no loss elastic no ˆ reliable transport between ˆ does not provide:
real-time audio/video loss-tolerant audio: 5kbps-1Mbps yes, 100’s msec sending and receiving process connection setup,
video:10kbps-5Mbps ˆ flow control: sender won’t reliability, flow control,
stored audio/video loss-tolerant same as above yes, few secs
overwhelm receiver congestion control, timing,
interactive games loss-tolerant few kbps up yes, 100’s msec throughput guarantee, or
ˆ congestion control: throttle
instant messaging no loss elastic yes and no security
sender when network
overloaded
ˆ does not provide: timing, Q: why bother? Why is
minimum throughput there a UDP?
guarantees, security
2: Application Layer 13 2: Application Layer 14

Internet apps: application, transport protocols Chapter2: Application layer


Application Underlying
Application layer protocol transport protocol ˆ Principles of network applications
™ Architecture: client-server or P2P
e-mail SMTP [RFC 2821] TCP
remote terminal access Telnet [RFC 854] ™ Services that an application needs
TCP
Web HTTP [RFC 2616] TCP ˆ important application-level protocols
file transfer FTP [RFC 959] TCP
streaming multimedia proprietary TCP or UDP ™ FTP, SMTP, P2P, ……
(e.g. RealNetworks)
ˆ programming network applications
Internet telephony proprietary
(e.g., Vonage,Dialpad) typically UDP ™ socket API

ˆ Web stuff
™ HTTP, DNS, Web searching

2: Application Layer 15 2: Application Layer 16

4
FTP: the file transfer protocol FTP: separate control, data connections
TCP control connection
ˆ FTP client contacts FTP port 21
FTP file transfer server at port 21, specifying
FTP FTP
user
interface
client server TCP as transport protocol
TCP data connection
user ˆ Client obtains authorization FTP port 20 FTP
local file remote file
at host over control connection client server
system system
ˆ Client browses remote
ˆ Server opens another TCP
ˆ transfer file to/from remote host
directory by sending
commands over control data connection to transfer
ˆ client/server model another file.
™client: side that initiates transfer (either to/from connection.
remote) ˆ Control connection: “out of
ˆ When server receives file
™ server: remote host transfer command, server band”
ˆ ftp: RFC 959 opens 2nd TCP connection (for ˆ FTP server maintains “state”:
ˆ ftp server file) to client current directory, earlier
™ Control connection: port 21 ˆ After transferring one file, authentication
™ Data connection: port 20
server closes data
2: Application Layer 17 connection. 2: Application Layer 18

FTP commands, responses Chapter2: Application layer


Sample commands: Sample return codes ˆ Principles of network applications
ˆ sent as ASCII text over ˆ status code and phrase (as
™ Architecture: client-server or P2P
control channel in HTTP)
ˆ USER username ˆ 331 Username OK, ™ Services that an application needs

ˆ PASS password password required ˆ learn about protocols by examining


ˆ LIST return list of file in
ˆ 125 data connection
already open;
important application-level protocols
current directory ™ Electronic Mail: SMTP, POP3, IMAP
transfer starting
ˆ RETR filename retrieves ˆ 425 Can’t open data ˆ Web searching
(gets) file connection
ˆ STOR filename stores ˆ 452 Error writing ˆ programming network applications
(puts) file onto remote file ™ socket API
host

2: Application Layer 19 2: Application Layer 20

5
Electronic Mail outgoing
message queue Electronic Mail: mail servers
user mailbox
user user
Three major components: agent Mail Servers agent
ˆ user agents mail ˆ mailbox contains incoming mail
user user
ˆ mail servers
server
agent messages for user server
agent
ˆ simple mail transfer SMTP ˆ message queue of outgoing
mail SMTP
protocol: SMTP (to be sent) mail messages mail
server user server user
ˆ SMTP protocol between mail
SMTP agent
SMTP agent
User Agent servers to send email
ˆ a.k.a. “mail reader” SMTP messages SMTP
user user
ˆ composing, editing, reading mail ™ client: sending mail mail
server agent agent
mail messages server server

ˆ e.g., Eudora, Outlook, elm, user ™ “server”: receiving mail


user
Netscape Messenger agent server agent
user user
ˆ outgoing, incoming messages agent agent
stored on server
2: Application Layer 21 2: Application Layer 22

Electronic Mail: SMTP [RFC 2821] Scenario: Alice sends message to Bob
1) Alice uses UA to compose 4) SMTP client sends Alice’s
message and “to” message over the TCP
ˆ uses TCP to reliably transfer email message from client
bob@someschool.edu connection
to server, port 25
2) Alice’s UA sends message 5) Bob’s mail server places the
ˆ direct transfer: sending server to receiving server
to her mail server; message message in Bob’s mailbox
ˆ three phases of transfer
placed in message queue 6) Bob invokes his user agent
™handshaking (greeting) 3) Client side of SMTP opens to read message
™transfer of messages TCP connection with Bob’s
™ closure mail server
ˆ command/response interaction
™ commands: ASCII text
™ response: status code and phrase 1
mail mail
server user
user
ˆ messages must be in 7-bit ASCII agent 2
server
agent
3 4 6
5

2: Application Layer 23 2: Application Layer 24

6
Sample SMTP interaction Try SMTP interaction for yourself:
S: 220 hamburger.edu
C: HELO crepes.fr ˆ telnet servername 25
S: 250 Hello crepes.fr, pleased to meet you
C: MAIL FROM: <alice@crepes.fr> ˆ see 220 reply from server
S: 250 alice@crepes.fr... Sender ok ˆ enter HELO, MAIL FROM, RCPT TO, DATA, QUIT
commands
C: RCPT TO: <bob@hamburger.edu>
S: 250 bob@hamburger.edu ... Recipient ok
C: DATA above lets you send email without using email client
S: 354 Enter mail, end with "." on a line by itself (reader)
C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery
C: QUIT
S: 221 hamburger.edu closing connection

2: Application Layer 25 2: Application Layer 26

SMTP: final words Mail message format

ˆ SMTP uses persistent Comparison with HTTP: SMTP: protocol for


connections exchanging email msgs header
ˆ HTTP: pull blank
ˆ SMTP requires message RFC 822: standard for text
ˆ SMTP: push line
(header & body) to be in 7- message format:
bit ASCII ˆ both have ASCII ˆ header lines, e.g.,
ˆ SMTP server uses command/response To:
™
body
CRLF.CRLF to determine interaction, status codes ™ From:
end of message ™ Subject:
ˆ HTTP: each object
different from SMTP
encapsulated in its own commands!
response msg
ˆ body
ˆ SMTP: multiple objects
™ the “message”, ASCII
sent in multipart msg characters only

2: Application Layer 27 2: Application Layer 28

7
Message format: multimedia extensions Mail access protocols
ˆ MIME: multimedia mail extension, RFC 2045, 2056 SMTP SMTP access user
ˆ additional lines in msg header declare MIME content user
agent protocol agent
type
sender’s mail receiver’s mail
From: alice@crepes.fr server server
MIME version
ˆ SMTP: delivery/storage to receiver’s server
To: bob@hamburger.edu
Subject: Picture of yummy crepe.
method used MIME-Version: 1.0 ˆ Mail access protocol: retrieval from server
to encode data Content-Transfer-Encoding: base64 ™ POP: Post Office Protocol [RFC 1939]
• authorization (agent <-->server) and download
Content-Type: image/jpeg
multimedia data
type, subtype, base64 encoded data ..... ™ IMAP: Internet Mail Access Protocol [RFC 1730]
parameter declaration ......................... • more features (more complex)
• manipulation of stored msgs on server
......base64 encoded data
encoded data
™ HTTP: Hotmail , Yahoo! Mail, etc.

2: Application Layer 29 2: Application Layer 30

POP3 protocol S: +OK POP3 server ready


POP3 (more) and IMAP
C: user bob
authorization phase S: +OK More about POP3 IMAP
ˆ Previous example uses
C: pass hungry
ˆ client commands: S: +OK user successfully logged on ˆ Keep all messages in
™ user: declare username “download and delete” one place: the server
C: list
™ pass: password S: 1 498 mode. ˆ Allows user to
ˆ server responses S: 2 912 ˆ Bob cannot re-read e- organize messages in
mail if he changes
S: .
™ +OK
C: retr 1 folders
™ -ERR S: <message 1 contents> client ˆ IMAP keeps user state
transaction phase, client: S: .
ˆ “Download-and-keep”: across sessions:
C: dele 1
ˆ list: list message numbers C: retr 2 copies of messages on ™ names of folders and
ˆ retr: retrieve message by S: <message 1 contents> different clients mappings between
number S: . message IDs and folder
ˆ POP3 is stateless
ˆ dele: delete
C: dele 2 name
C: quit across sessions
ˆ quit S: +OK POP3 server signing off
2: Application Layer 31 2: Application Layer 32

8
P2P file sharing
Chapter2: Application layer
Example ˆ Alice chooses one of
the peers, Bob.
ˆ Principles of network applications ˆ Alice runs P2P client
application on her ˆ File is copied from
™ Architecture: client-server or P2P
notebook computer Bob’s PC to Alice’s
™ Services that an application needs notebook: HTTP
ˆ Intermittently
ˆ important application-level protocols connects to Internet; ˆ While Alice downloads,
™ P2P gets new IP address other users uploading
for each connection from Alice.
ˆ programming network applications
ˆ Asks for “Primal Fear” ˆ Alice’s peer is both a
™ socket API
Web client and a
ˆ Application displays
ˆ Web stuff transient Web server.
other peers that have
™ HTTP, DNS, Web searching copy of Primal Fear. All peers are servers =
highly scalable!
2: Application Layer 33 2: Application Layer 34

Pure P2P architecture File Distribution: Server-Client vs P2P


Question : How much time to distribute file
ˆ no always-on server from one server to N peers?
ˆ arbitrary end systems
directly communicate peer-peer us: server upload
bandwidth
Server
ˆ peers are intermittently
ui: peer i upload
connected and change IP bandwidth
u2
addresses
u1 d1
us d2
di: peer i download
File, size F bandwidth
ˆ Three topics: dN
Network (with
™ File distribution abundant bandwidth)
uN
™ Searching for information
™ Case Study: Skype

2: Application Layer 35 2: Application Layer 36

9
File distribution time: server-client File distribution time: P2P
Server Server
ˆ server sequentially F u1 d1 u2
ˆ server must send one F u1 d1 u2
sends N copies: us d2 copy: F/us time us d2

NF/us time ˆ client i takes F/di time


™ Network (with Network (with
to download
dN dN
abundant bandwidth) abundant bandwidth)
ˆ client i takes F/di
ˆ NF bits must be
uN uN
time to download downloaded (aggregate)
ˆ fastest possible upload rate: us + Σui

Time to distribute F
to N clients using = dcs = max { NF/us, F/min(di) }
i
client/server approach
dP2P = max { F/us, F/min(di) , NF/(us + Σui) }
increases linearly in N i
(for large N) 2: Application Layer 37 2: Application Layer 38

Server-client vs. P2P: example File distribution: BitTorrent


Client upload rate = u, F/u = 1 hour, us = 10u, dmin ≥ us ˆ P2P file distribution
3.5 tracker: tracks peers torrent: group of
P2P participating in torrent peers exchanging
Minimum Distribution Time

chunks of a file
3
Client-Server
2.5

1.5
obtain list
of peers
1
trading
0.5
chunks

0
0 5 10 15 20 25 30 35
peer
N
2: Application Layer 39 2: Application Layer 40

10
BitTorrent (2) Sending Chunks: tit-for-tat
BitTorrent (1) Pulling Chunks ˆ Alice sends chunks to four
neighbors currently
ˆ at any given time,
ˆ file divided into 256KB chunks. sending her chunks at the
different peers have highest rate
ˆ peer joining torrent: different subsets of
file chunks ™re-evaluate top 4 every
™ has no chunks, but will accumulate them over time
10 secs
™ registers with tracker to get list of peers, ˆ periodically, a peer
ˆ every 30 secs: randomly
connects to subset of peers (“neighbors”) (Alice) asks each
neighbor for list of select another peer,
ˆ while downloading, peer uploads chunks to other starts sending chunks
peers. chunks that they have.
™ newly chosen peer may
ˆ peers may come and go ˆ Alice sends requests
for her missing chunks join top 4
ˆ once peer has entire file, it may (selfishly) leave or ™ “optimistically unchoke”
(altruistically) remain ™ rarest first

2: Application Layer 41 2: Application Layer 42

P2P: searching for information


BitTorrent: Tit-for-tat
Index in P2P system: maps information to peer location
(1) Alice “optimistically unchokes” Bob
(location = IP address & port number)
(2) Alice becomes one of Bob’s top-four providers; Bob reciprocates
(3) Bob becomes one of Alice’s top-four providers . Instant messaging
File sharing (eg e-mule)
ˆ Index dynamically ˆ Index maps user
tracks the locations of names to locations.
files that peers share. ˆ When user starts IM
ˆ Peers need to tell application, it needs to
index what they have. inform index of its
ˆ Peers search index to
location
determine where files ˆ Peers search index to
can be found determine IP address
With higher upload rate, of user.
can find better trading
partners & get file faster!
2: Application Layer 43 2: Application Layer 44

11
P2P: centralized index P2P: problems with centralized directory
Bob
original “Napster” design centralized
ˆ single point of failure file transfer is
1) when peer connects, it directory server
1 ˆ performance bottleneck decentralized, but
informs central server: peers ˆ copyright infringement:
locating content is
™ IP address 1
“target” of lawsuit is highly centralized
™ content obvious
1 3
2) Alice queries for “Hey
2
Jude” 1

3) Alice requests file from


Bob

Alice

2: Application Layer 45 2: Application Layer 46

Query flooding Query flooding


File transfer:
ˆ Query message HTTP
ˆ fully distributed overlay network: graph sent over existing TCP
™ no central server ˆ edge between peer X connections
Query
ˆ used by Gnutella and Y if there’s a TCP ˆ peers forward
QueryHit
ˆ Each peer indexes the connection Query message
files it makes available ˆ all active peers and ˆ QueryHit er
y Qu
e
Qu ry
for sharing (and no edges form overlay net sent over yH
it
er
other files) u
ˆ edge: virtual (not reverse Q

physical) link path Query


QueryHit
ˆ given peer typically
connected with < 10 Scalability: Qu
er
overlay neighbors y
limited scope
flooding
2: Application Layer 47 2: Application Layer 48

12
Gnutella: Peer joining Hierarchical Overlay
1. joining peer Alice must find another peer in ˆ between centralized
Gnutella network: use list of candidate peers index, query flooding
2. Alice sequentially attempts TCP connections with approaches
candidate peers until connection setup with Bob ˆ each peer is either a
3. Flooding: Alice sends Ping message to Bob; Bob super node or assigned to
forwards Ping message to his overlay neighbors a super node
(who then forward to their neighbors….)
™ TCP connection between
ˆ peers receiving Ping message respond to Alice peer and its super node.
with Pong message ™ TCP connections between
4. Alice receives many Pong messages, and can then some pairs of super nodes. ordinary peer

setup additional TCP connections ˆ Super node tracks content group-leader peer

Peer leaving: see homework problem! (p20) in its children neighoring relationships
in overlay network

2: Application Layer 49 2: Application Layer 50

P2P Case study: Skype Peers as relays


Skype clients (SC)
ˆ inherently P2P: pairs ˆ Problem when both
of users communicate. Alice and Bob are
behind “NATs”.
ˆ proprietary Skype
Supernode ™ NAT prevents an outside
application-layer login server peer from initiating a call
protocol (inferred via (SN) to insider peer
reverse engineering) ˆ Solution:
ˆ hierarchical overlay ™ Using Alice’s and Bob’s
SNs, Relay is chosen
with SNs
™ Each peer initiates
ˆ Index maps usernames session with relay.
to IP addresses; ™ Peers can now
distributed over SNs communicate through
NATs via relay

2: Application Layer 51 2: Application Layer 52

13
Socket programming Socket-programming using TCP
Goal: learn how to build client/server application that Socket: a door between application process and end-
communicate using sockets end-transport protocol (UCP or TCP)
Socket API socket TCP service: reliable transfer of bytes from one
ˆ introduced in BSD4.1 UNIX, process to another
a host-local,
1981 application-created,
ˆ explicitly created, used, OS-controlled interface controlled by
released by apps controlled by
(a “door”) into which process process application
application developer
ˆ client/server paradigm application process can developer socket
socket
ˆ two types of transport both send and TCP with controlled by
controlled by TCP with
service via socket API: receive messages to/from operating buffers, buffers, operating
internet variables system
another application system variables
™ unreliable datagram
process
™ reliable, byte stream- host or
host or
oriented server
server
2: Application Layer 53 2: Application Layer 54

Socket programming with TCP Client/server socket interaction: TCP


Client must contact server ˆ When contacted by client, Server (running on hostid) Client
ˆ server process must first server TCP creates new create socket,
be running socket for server process to port=x, for

ˆ server must have created communicate with client incoming request:


welcomeSocket =
socket (door) that ™ allows server to talk with ServerSocket()

welcomes client’s contact multiple clients TCP create socket,


wait for incoming
™ source port numbers connection request connection setup connect to hostid, port=x
Client contacts server by: clientSocket =
used to distinguish connectionSocket =
ˆ creating client-local TCP welcomeSocket.accept() Socket()
clients (more in Chap 3)
socket send request using
ˆ specifying IP address, port
read request from clientSocket
application viewpoint connectionSocket
number of server process
TCP provides reliable, in-order write reply to
ˆ When client creates
transfer of bytes (“pipe”) connectionSocket read reply from
socket: client TCP
between client and server clientSocket
establishes connection to close
close
server TCP
connectionSocket
clientSocket
2: Application Layer 55 2: Application Layer 56

14
Stream jargon Socket programming with TCP
keyboard monitor

ˆ A stream is a sequence of Example client-server app:


characters that flow into 1) client reads line from

inFromUser
or out of a process. input
stream
standard input (inFromUser
ˆ An input stream is Client stream) , sends to server via
attached to some input Process socket (outToServer
process
source for the process, stream)
e.g., keyboard or socket. 2) server reads line from socket
ˆ An output stream is 3) server converts line to
attached to an output uppercase, sends back to

inFromServer
outToServer
source, e.g., monitor or client
output input
stream stream

socket. 4) client reads, prints modified


client TCP
clientSocket line from socket
socket TCP
(inFromServer stream)
socket

to network from network

2: Application Layer 57 2: Application Layer 58

Example: Java client (TCP) Example: Java client (TCP), cont.


import java.io.*;
import java.net.*; Create BufferedReader inFromServer =
class TCPClient { input stream new BufferedReader(new
attached to socket InputStreamReader(clientSocket.getInputStream()));
public static void main(String argv[]) throws Exception
{ sentence = inFromUser.readLine();
String sentence;
String modifiedSentence; Send line
to server outToServer.writeBytes(sentence + '\n');
Create
input stream BufferedReader inFromUser =
Read line modifiedSentence = inFromServer.readLine();
new BufferedReader(new InputStreamReader(System.in));
from server
Create System.out.println("FROM SERVER: " + modifiedSentence);
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server clientSocket.close();
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream()); }
attached to socket }
2: Application Layer 59 2: Application Layer 60

15
Example: Java server (TCP) Example: Java server (TCP), cont
import java.io.*;
import java.net.*;
Create output
class TCPServer { stream, attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
public static void main(String argv[]) throws Exception
{ Read in line
String clientSentence;
from socket clientSentence = inFromClient.readLine();
Create String capitalizedSentence;
welcoming socket capitalizedSentence = clientSentence.toUpperCase() + '\n';
ServerSocket welcomeSocket = new ServerSocket(6789);
at port 6789 Write out line
outToClient.writeBytes(capitalizedSentence);
Wait, on welcoming while(true) { to socket
}
socket for contact Socket connectionSocket = welcomeSocket.accept(); }
by client } End of while loop,
BufferedReader inFromClient = loop back and wait for
Create input
stream, attached
new BufferedReader(new another client connection
InputStreamReader(connectionSocket.getInputStream()));
to socket

2: Application Layer 61 2: Application Layer 62

Socket programming with UDP Client/server socket interaction: UDP


Server (running on hostid) Client
UDP: no “connection” between
client and server create socket, create socket,
ˆ no handshaking port=x, for clientSocket =
incoming request:
ˆ sender explicitly attaches
DatagramSocket()
application viewpoint serverSocket =
IP address and port of DatagramSocket()

destination to each packet UDP provides unreliable transfer Create, address (hostid, port=x,
of groups of bytes (“datagrams”) send datagram request
ˆ server must extract IP using clientSocket
between client and server read request from
address, port of sender serverSocket

from received packet


write reply to
UDP: transmitted data may be serverSocket
specifying client read reply from
received out of order, or host address, clientSocket

lost port number close


clientSocket

2: Application Layer 63 2: Application Layer 64

16
Example: Java client (UDP) Example: Java client (UDP)
keyboard monitor

import java.io.*;
import java.net.*;

inFromUser
input
stream
class UDPClient {
Client
Process public static void main(String args[]) throws Exception
Input: receives
process Create
{
packet (recall
thatTCP received input stream BufferedReader inFromUser =
Output: sends
packet (recall “byte stream”) Create
new BufferedReader(new InputStreamReader(System.in));

receivePacket
sendPacket
that TCP sent UDP UDP
client socket DatagramSocket clientSocket = new DatagramSocket();
packet packet
“byte stream”) Translate
InetAddress IPAddress = InetAddress.getByName("hostname");
client UDP hostname to IP
clientSocket
socket UDP
address using DNS byte[] sendData = new byte[1024];
socket
byte[] receiveData = new byte[1024];
to network from network

String sentence = inFromUser.readLine();


sendData = sentence.getBytes();
2: Application Layer 65 2: Application Layer 66

Example: Java client (UDP), cont. Example: Java server (UDP)


Create datagram import java.io.*;
with data-to-send, DatagramPacket sendPacket = import java.net.*;
length, IP addr, port new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
class UDPServer {
Send datagram clientSocket.send(sendPacket); public static void main(String args[]) throws Exception
to server Create {
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
Read datagram
clientSocket.receive(receivePacket);
from server byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
String modifiedSentence =
new String(receivePacket.getData()); while(true)
{
System.out.println("FROM SERVER:" + modifiedSentence);
Create space for
clientSocket.close();
}
received datagram DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
} Receive serverSocket.receive(receivePacket);
datagram
2: Application Layer 67 2: Application Layer 68

17
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
InetAddress IPAddress = receivePacket.getAddress();
port #, of
sender int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
DatagramPacket sendPacket =
to send to client new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram serverSocket.send(sendPacket);
to socket }
}
} End of while loop,
loop back and wait for
another datagram
2: Application Layer 69

18

Anda mungkin juga menyukai