Chapter 2: Application layer

73
2: Application Layer 1 Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP 2.7 Socket programming with UDP 2.8 Socket programming with TCP

description

2.1 Principles of network applications 2.2 Web and HTTP 2.4 Electronic Mail SMTP, POP3, IMAP. 2.7 Socket programming with UDP 2.8 Socket programming with TCP. Chapter 2: Application layer. e-mail web instant messaging remote login P2P file sharing multi-user network games - PowerPoint PPT Presentation

Transcript of Chapter 2: Application layer

Page 1: Chapter 2: Application layer

2: Application Layer 1

Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.4 Electronic Mail

SMTP, POP3, IMAP

2.7 Socket programming with UDP

2.8 Socket programming with TCP

Page 2: Chapter 2: Application layer

2: Application Layer 2

Some network apps e-mail web instant messaging remote login P2P file sharing multi-user network games streaming stored video clips

social networks voice over IP real-time video conferencing

Page 3: Chapter 2: Application layer

2: Application Layer 3

Creating a network appwrite programs that

run on (different) end systems

communicate over network

e.g., browser software communicates with web server software

No need to write software for network-core devices Network-core devices do

not run user applications

application

transportnetworkdata linkphysical

application

transportnetworkdata linkphysical

application

transportnetworkdata linkphysical

Page 4: Chapter 2: Application layer

2: Application Layer 4

Chapter 2: Application layer 2.1 Principles of network applications

2.2 Web and HTTP 2.4 Electronic Mail

SMTP, POP3, IMAP

2.7 Socket programming with UDP

2.8 Socket programming with TCP

Page 5: Chapter 2: Application layer

2: Application Layer 5

Application architecturesHow the application is structured over

various end systems Client-server Peer-to-peer (P2P) Hybrid of client-server and P2P

Network architecture: e.g., the TCP/IP protocol stack, OSI

Page 6: Chapter 2: Application layer

2: Application Layer 6

Client-server architectureserver:

always-on host permanent IP

address server

farms/clusters for scaling

clients: communicate with

server may be intermittently

connected may have dynamic IP

addresses do not communicate

directly with each other

client/server

Page 7: Chapter 2: Application layer

Server Farm (or Cluster)

2: Application Layer 7

Page 8: Chapter 2: Application layer

Google Data Centers Estimated cost of data center: $600M Google spent $2.4B in 2007 on new

data centers Each data center uses 50-100

megawatts of power with thousands of servers

Page 9: Chapter 2: Application layer

2: Application Layer 9

Pure P2P architecture no always-on server arbitrary end systems

directly communicate peers are

intermittently connected and change IP addresses

Highly scalable but difficult to manage

peer-peer

Page 10: Chapter 2: Application layer

2: Application Layer 10

Hybrid of client-server and P2PSkype

voice-over-IP P2P application centralized server: finding address of

remote party client-client connection: direct (not through

server)

Page 11: Chapter 2: Application layer

2: Application Layer 11

Processes communicatingProcess: program

running within a host. within same host, two

processes communicate using inter-process communication (defined by OS).

processes in different hosts communicate by exchanging messages

Client process: initiates communication

Server process: waits to be contacted

Note: applications with P2P architectures have client processes & server processes

Page 12: Chapter 2: Application layer

2: Application Layer 12

Sockets process sends/receives

messages to/from its socket

socket analogous to mailbox sending process leaves

message in socket transport infrastructure

brings message to socket at receiving process

process

TCP withbuffers,variables

socket

host orserver

process

TCP withbuffers,variables

socket

host orserver

Internet

controlledby OS

controlled byapp developer

Page 13: Chapter 2: Application layer

2: Application Layer 13

Addressing processes to receive messages, process must have

identifier: IP address and port number associated with that process.

host device has unique 32-bit IP address Exercise: use ipconfig from command prompt to get

your IP address (Windows)

example port numbers: HTTP server: 80 Mail server: 25

Page 14: Chapter 2: Application layer

2: Application Layer 14

App-layer protocol defines Types of messages

exchanged, e.g., request, response

Message syntax: what fields in

messages & how fields are delineated

Message semantics meaning of information

in fields Rules for when and

how processes send & respond to messages

Public-domain protocols:

defined in RFCs allows for

interoperability e.g., HTTP, SMTP,

BitTorrentProprietary protocols: e.g., Skype,

ppstream

Page 15: Chapter 2: Application layer

2: Application Layer 15

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

Timing some apps (e.g.,

Internet telephony, interactive games) require low delay to be “effective”

Throughput some apps (e.g.,

multimedia) require minimum amount of throughput to be “effective”

other apps (“elastic apps”) make use of whatever throughput they get

Security Encryption, data

integrity, …

Page 16: Chapter 2: Application layer

2: Application Layer 16

Internet transport protocols services

TCP service: connection-oriented: setup

required between client and server processes

reliable transport between sending and receiving process

flow control: sender won’t overwhelm receiver

congestion control: throttle sender when network overloaded

does not provide: timing, minimum throughput guarantees, security

UDP service: connectionless unreliable data transfer

between sending and receiving process

does not provide: connection setup, reliability, flow control, congestion control, timing, throughput guarantee, or security

Page 17: Chapter 2: Application layer

2: Application Layer 17

Internet apps: application, transport protocols

Application

e-mailremote terminal access

Web file transfer

streaming multimedia

Internet telephony

Applicationlayer protocol

SMTP [RFC 2821]Telnet [RFC 854]HTTP [RFC 2616]FTP [RFC 959]HTTP (eg Youtube), RTP [RFC 1889]SIP, RTP, proprietary(e.g., Skype)

Underlyingtransport protocol

TCPTCPTCPTCPTCP or UDP

typically UDP

Page 18: Chapter 2: Application layer

2: Application Layer 18

Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.4 Electronic Mail

SMTP, POP3, IMAP

2.7 Socket programming with UDP

2.8 Socket programming with TCP

Page 19: Chapter 2: Application layer

2: Application Layer 19

Web and HTTPFirst some jargon Web page consists of objects Object can be HTML file, JPEG image, Java

applet, audio file,… Web page typically consists of base HTML-file

which includes several referenced objects Each object is addressable by a URL Example URL:

www.cse.ohio-state.edu/~lai/pic.jpg www.cse.ohio-state.edu/~lai/pic.jpg

host name path name

Page 20: Chapter 2: Application layer

2: Application Layer 20

HTTP overviewHTTP: hypertext transfer protocol Web’s application layer protocol client/server model

client: browser that requests, receives, “displays” Web objects

server: Web server sends objects in response to requests

PC runningExplorer

Server running

Apache Webserver

Mac runningNavigator

HTTP request

HTTP request

HTTP response

HTTP response

Page 21: Chapter 2: Application layer

2: Application Layer 21

HTTP overview (continued)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

HTTP is “stateless” server maintains no

information about past client requests

Protocols that maintain “state” are complex!

past history (state) must be maintained

aside

Page 22: Chapter 2: Application layer

2: Application Layer 22

process

TCP

socket

client

process

TCP

socket

Web server

Internet

Port 80

Page 23: Chapter 2: Application layer

2: Application Layer 23

HTTP connectionsNonpersistent HTTP At most one object is sent over a TCP

connection.

Persistent HTTP Multiple objects can be sent over single TCP

connection between client and server.

Page 24: Chapter 2: Application layer

2: Application Layer 24

Nonpersistent HTTPSuppose user enters URL

www.someSchool.edu/someDepartment/home.index

1a. HTTP client initiates TCP connection to HTTP server (process) at www.someSchool.edu on port 80

2. HTTP client sends HTTP request message (containing URL) into TCP connection socket. Message indicates that client wants object someDepartment/home.index

1b. HTTP server at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection, notifying client

3. HTTP server receives request message, forms response message containing requested object, and sends message into its sockettime

(contains text, references to 10

jpeg images)

Page 25: Chapter 2: Application layer

2: Application Layer 25

Nonpersistent HTTP (cont.)

5. HTTP client receives response message containing html file, displays html. Parsing html file, finds 10 referenced jpeg objects6. Steps 1-5 repeated for each of 10 jpeg objects

4. HTTP server closes TCP connection.

time

Page 26: Chapter 2: Application layer

2: Application Layer 26

Non-Persistent HTTP: Response timeDefinition of RTT: time for

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 timetotal = 2RTT+transmit

time

time to transmit file

initiate TCPconnection

RTTrequestfile

RTT

filereceived

time time

Page 27: Chapter 2: Application layer

2: Application Layer 27

Persistent HTTP

Nonpersistent HTTP: requires 2 RTTs per object OS overhead for each TCP

connection browsers often open

parallel TCP connections to fetch referenced objects

Persistent HTTP server leaves connection

open after sending response

subsequent HTTP messages between same client/server sent over open connection

client sends requests as soon as it encounters a referenced object

as little as one RTT for all the referenced objects

Page 28: Chapter 2: Application layer

2: Application Layer 28

HTTP request message two types of HTTP messages: request,

response HTTP request message:

ASCII (human-readable format)

GET /somedir/page.html HTTP/1.1Host: www.someschool.edu User-agent: Mozilla/4.0Connection: close Accept-language:fr

(extra carriage return, line feed)

request line(GET, POST,

HEAD commands)

header lines

Carriage return, line feed

indicates end of message

Page 29: Chapter 2: Application layer

2: Application Layer 29

HTTP request message: general format

Page 30: Chapter 2: Application layer

2: Application Layer 30

Method typesHTTP/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

Page 31: Chapter 2: Application layer

2: Application Layer 31

HTTP response message

HTTP/1.1 200 OK Connection: closeDate: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 …... Content-Length: 6821 Content-Type: text/html data data data data data ...

status line(protocol

status codestatus phrase)

header lines

data, e.g., requestedHTML file

Page 32: Chapter 2: Application layer

2: Application Layer 32

HTTP response status codes

200 OK request succeeded, requested object later in this

message301 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

In first line in server->client response message.A few sample codes:

Page 33: Chapter 2: Application layer

2: Application Layer 33

User-server state: cookiesMany major Web sites use cookiesFour components:

1) cookie header line of HTTP response message2) cookie header line in HTTP request message3) cookie file kept on user’s host, managed by user’s

browser4) back-end database at Web site

Example: Susan always access

Internet always from PC

visits specific e-commerce site for first time

when initial HTTP requests arrives at site, site creates: unique ID entry in backend

database for ID

Page 34: Chapter 2: Application layer

2: Application Layer 34

Cookies: keeping “state” (cont.)client server

usual http response msg

usual http response msg

cookie file

one week later:

usual http request msg

cookie: 1678cookie-specificaction

access

ebay 8734 usual http request msg Amazon server

creates ID1678 for usercreate

entryusual http response Set-cookie: 1678

ebay 8734amazon 1678

usual http request msg

cookie: 1678cookie-spectificaction

accessebay 8734amazon 1678

backenddatabase

Page 35: Chapter 2: Application layer

2: Application Layer 35

Cookies (continued)What cookies can

bring: authorization shopping carts recommendations

Cookies and privacy: cookies permit sites

to learn a lot about you

aside

Page 36: Chapter 2: Application layer

2: Application Layer 36

http://tools.ietf.org/html/rfc2616

HTTP is defined in RFC 2616

Page 37: Chapter 2: Application layer

2: Application Layer 37

Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP

2.4 Electronic Mail SMTP, POP3, IMAP

2.7 Socket programming with UDP

2.8 Socket programming with TCP

Page 38: Chapter 2: Application layer

Electronic MailMajor components: user agents mail servers message submission

protocol (e.g. SMTP) simple mail transfer

protocol: SMTP mail access protocol (e.g.

POP3)

User Agent a.k.a. “mail reader” composing, editing,

reading mail messages e.g., Eudora, Outlook,

elm, Mozilla Thunderbird

2: Application Layer 38

useragen

t

sender’s mail server

useragent

submissionprotocol

SMTP accessprotocol

receiver’s mail server

Page 39: Chapter 2: Application layer

2: Application Layer 39

Scenario: Alice sends message to Bob1) Alice uses UA to compose

message and “to” [email protected]

2) Alice’s UA sends message to her mail server; message placed in message queue

3) Client side of SMTP opens TCP connection with Bob’s mail server

4) SMTP client sends Alice’s message over the TCP connection

5) Bob’s mail server places the message in Bob’s mailbox

6) Bob invokes his user agent to read message

useragent

mailserver

mailserver user

agent

1

2 3 4 56

Page 40: Chapter 2: Application layer

2: Application Layer 40

Electronic Mail: mail serversMail Servers e.g. mail server at cse.ohio-state.edu 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

messages “server”: receiving

messages

mailserver

useragent

useragent

useragentmail

server

useragent

useragent

mailserver

useragent

SMTP

SMTP

SMTP

user mailbox

outgoing message queue

Page 41: Chapter 2: Application layer

2: Application Layer 41

Electronic Mail: SMTP [RFC 2821]

uses TCP to reliably transfer email message from client to server, port 25

direct transfer: sending server to receiving server three phases of transfer

handshaking (greeting) transfer of messages closure

command/response interaction commands: ASCII text response: status code and phrase

messages must be in 7-bit ASCII

Page 42: Chapter 2: Application layer

2: Application Layer 42

Sample SMTP interaction S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <[email protected]> S: 250 [email protected]... Sender ok C: RCPT TO: <[email protected]> S: 250 [email protected] ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: Do you like ketchup? C: How about pickles? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection

Page 43: Chapter 2: Application layer

2: Application Layer 43

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

Page 44: Chapter 2: Application layer

2: Application Layer 44

Mail access protocols

SMTP: delivery/storage to receiver’s server Mail access protocol: retrieval from server

POP: Post Office Protocol [RFC 1939]• authorization (agent <-->server) and

download IMAP: Internet Mail Access Protocol [RFC 1730]

• more features (more complex)• manipulation of stored msgs on server

HTTP: gmail, Hotmail, Yahoo! Mail, etc.

useragent

sender’s mail server

useragent

SMTP SMTP accessprotocol

receiver’s mail server

Page 45: Chapter 2: Application layer

2: Application Layer 45

POP3 protocolauthorization phase client commands:

user: declare username

pass: password server responses

+OK -ERR

transaction phase, client: list: list message

numbers retr: retrieve message

by number dele: delete quit

C: list S: 1 498 S: 2 912 S: . C: retr 1 S: <message 1 contents> S: . C: dele 1 C: retr 2 S: <message 1 contents> S: . C: dele 2 C: quit S: +OK POP3 server signing off

S: +OK POP3 server ready C: user bob S: +OK C: pass hungry S: +OK user successfully logged on

Page 46: Chapter 2: Application layer

2: Application Layer 46

POP3 (more) and IMAPMore about POP3 Previous example

uses “download and delete” mode.

Bob cannot re-read e-mail if he changes client

“Download-and-keep”: copies of messages on different clients

POP3 is stateless across sessions

IMAP Keep all messages in

one place: the server Allows user to

organize messages in folders

IMAP keeps user state across sessions: names of folders and

mappings between message IDs and folder name

Page 47: Chapter 2: Application layer

2: Application Layer 47

Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP

2.7 Socket programming with UDP

2.8 Socket programming with TCP

Page 48: Chapter 2: Application layer

2: Application Layer 48

Socket programming

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: UDP TCP

An application-created, OS-controlled interface (a “door”) thru which

application process can both send and

receive messages to/from another

application process

socket

Goal: see an example of client/server application that communicate using sockets

Page 49: Chapter 2: Application layer

2: Application Layer 49

process

UDP/TCP

socket

server

process

UDP/TCP

socket

client

Internet

Port #

Page 50: Chapter 2: Application layer

Socket programming basics Server must be

running before client can send anything to it.

Server must have a socket (door) through which it receives and sends segments

Similarly client needs a socket

Socket is locally identified with a port number Analogous to the apt

# in a building Client needs to know

server IP address and socket port number.

2: Application Layer 50

Page 51: Chapter 2: Application layer

2: Application Layer 51

Socket programming with UDP

UDP: no “connection” between client and server

no handshaking sender explicitly attaches

IP address and port of destination to each segment

OS attaches IP address and port of sending socket to each segment

Server can extract IP address, port of sender from received segment

application viewpointUDP provides unreliable

transfer of “datagrams” between

client and server

Note: the official terminology for a UDP packet is “datagram”. In this class, we instead use “UDP segment”.

Page 52: Chapter 2: Application layer

2: Application Layer 52

socket socket

UDP UDP

Process Process

Port 9876 Port 9999

Page 53: Chapter 2: Application layer

Running example Client:

User types line of text Client program sends line to server

Server: Server receives line of text Capitalizes all the letters Sends modified line to client

Client: Receives line of text Displays

2: Application Layer 53

Page 54: Chapter 2: Application layer

2: Application Layer 54

Client/server socket interaction: UDPServer (running on hostid)

closeclientSocket

read datagram fromclientSocket

create socket,clientSocket = DatagramSocket()

Client

Create datagram with server IP andport=x; send datagram via clientSocket

create socket,port= x.serverSocket = DatagramSocket()

read datagram fromserverSocket

write reply toserverSocketspecifying client address,port number

Page 55: Chapter 2: Application layer

2: Application Layer 55

Example: Java client (UDP)

send

Pac

ket

to network from network

rece

iveP

acke

t

inFr

omU

ser

keyboard monitor

Process

clientSocket

UDPpacket

inputstream

UDPpacket

UDPsocket

Output: sends packet (will seethat TCP sent “byte stream”)

Input: receives packet (will see thatTCP received “byte stream”)

Clientprocess

client UDP socket

Page 56: Chapter 2: Application layer

2: Application Layer 56

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 byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine();

sendData = sentence.getBytes();

Createinput stream

Create client socket

Translate hostname to IP

address using DNS

Page 57: Chapter 2: Application layer

2: Application Layer 57

Example: Java client (UDP), cont. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence);

clientSocket.close(); }

}

Create datagram with data-to-send,

length, IP addr, port

Send datagramto server

Read datagramfrom server

Page 58: Chapter 2: Application layer

2: Application Layer 58

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 byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

serverSocket.receive(receivePacket);

Createdatagram socket

at port 9876

Create space forreceived datagram

Receivedatagra

m

Page 59: Chapter 2: Application layer

2: Application Layer 59

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(sendPacket); } }

}

Get IP addrport #, of

sender

Write out datagramto socket

End of while loop,loop back and wait foranother datagram

Create datagramto send to client

Page 60: Chapter 2: Application layer

UDP observations & questions Both client server use DatagramSocket Dest IP and port are explicitly attached to

segment. What would happen if change both

clientSocket and serverSocket to “mySocket”?

Can the client send a segment to server without knowing the server’s IP address and/or port number?

Can multiple clients use the server?2: Application Layer 60

Page 61: Chapter 2: Application layer

2: Application Layer 61

Chapter 2: Application layer 2.1 Principles of network applications 2.2 Web and HTTP 2.3 FTP 2.4 Electronic Mail

SMTP, POP3, IMAP 2.5 DNS

2.6 P2P applications 2.7 Socket

programming with UDP

2.8 Socket programming with TCP

Page 62: Chapter 2: Application layer

2: Application Layer 62

welcome socket

socket socket

TCP TCP

Process Process

Port 6789 Port 6789Port 9999

Host S Host C

Page 63: Chapter 2: Application layer

2: Application Layer 63

Socket-programming using TCP

TCP service: reliable transfer of bytes from one process to another

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperating

system

host orserver

process

TCP withbuffers,

variables

socket

controlled byapplicationdevelopercontrolled byoperatingsystem

host orserver

internet

Page 64: Chapter 2: Application layer

2: Application Layer 64

Socket programming with TCPClient must contact server server process must first

be running server must have

created socket (door) that welcomes client’s contact

Client contacts server by: creating client-local TCP

socket specifying IP address,

port number of server process

When client creates socket: client TCP establishes connection to server 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)

TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server

application viewpoint

Page 65: Chapter 2: Application layer

2: Application Layer 65

Client/server socket interaction: TCP

wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()

create socket,port=x, forincoming request:welcomeSocket =

ServerSocket()

create socket,connect to hostid, port=xclientSocket =

Socket()

closeconnectionSocket

read reply fromclientSocket

closeclientSocket

Server (running on hostid) Client

send request usingclientSocketread request from

connectionSocket

write reply toconnectionSocket

TCP connection setup

Page 66: Chapter 2: Application layer

2: Application Layer 66ou

tToS

erve

r

to network from network

inFr

omS

erve

r

inFr

omU

ser

keyboard monitor

Process

clientSocket

inputstream

inputstream

outputstream

TCPsocket

Clientprocess

client ccTCP

socketc

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, e.g., keyboard or socket. An output stream is attached to an output source, e.g.,

monitor or socket.

Page 67: Chapter 2: Application layer

2: Application Layer 67

Socket programming with TCPExample 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)

Page 68: Chapter 2: Application layer

2: Application Layer 68

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());

Createinput stream

Create client socket,

connect to serverCreate

output streamattached to socket

Page 69: Chapter 2: Application layer

2: Application Layer 69

Example: Java client (TCP), cont.

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(); } }

Createinput stream

attached to socket

Send lineto server

Read linefrom server

Page 70: Chapter 2: Application layer

2: Application Layer 70

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()));

Createwelcoming socket

at port 6789Wait, on welcoming

socket for contactby client

Create inputstream, attached

to socket

Page 71: Chapter 2: Application layer

2: Application Layer 71

Example: Java server (TCP), cont

DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence); } } }

Read in linefrom socket

Create outputstream,

attached to socket

Write out lineto socket

End of while loop,loop back and wait foranother client connection

Page 72: Chapter 2: Application layer

TCP observations & questions Server has two types of sockets:

ServerSocket and Socket When client knocks on serverSocket’s

“door,” server creates connectionSocket and completes TCP conx.

Dest IP and port are not explicitly attached to segment.

Can multiple clients use the server?

2: Application Layer 72

Page 73: Chapter 2: Application layer

2: Application Layer 73

Chapter 2: Summary

application architectures client-server P2P hybrid

application service requirements: reliability, bandwidth,

delay Internet transport

service model connection-oriented,

reliable: TCP unreliable, datagrams:

UDP

our study of network apps now complete! specific protocols:

HTTP SMTP, POP, IMAP

socket programming