2: Application Layer 1
From last Lecture Applications and application-layer
protocols Client and server Socket
Port number Transport protocol services
How to choose
2: Application Layer 2
Chapter 2: Application layer
2.1 Principles of network applications 2.2 Web and HTTP 2.7 Socket programming with TCP 2.9 Building a Web server 2.8 Socket programming with UDP 2.3 FTP 2.4 Electronic Mail
SMTP, POP3, IMAP
2.5 DNS 2.6 P2P file sharing
2: Application Layer 3
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:
reliable, byte stream-oriented (TCP) unreliable datagram (UDP)
Goal: learn how to build client/server application that communicate using sockets
2: Application Layer 4
Socket programming
Socket API:
a host-local, application-created/owned, OS-controlled interface (a “door”) into which application process can both send and receive messages to/from another (remote or local) application process
socket
Createsocket
Establishconnection
Send/recvdata
close thesocket
2: Application Layer 5
Socket programming using TCP
Socket API: Createsocket
Establishconnection
Send/recvdata
close thesocket
process
TCP withbuffers,
variables
socket
controlled byapplicationdeveloper
controlled byoperating
system
host
process
TCP withbuffers,
variables
socket
controlled byapplicationdeveloper
controlled byoperatingsystem
server
internet
2: Application Layer 6
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
2: Application Layer 7
2: Application Layer 8
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.
2: Application Layer 9
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 socket3) server converts line to
uppercase, sends back to client
4) client reads, prints modified line from socket (inFromServer stream)
outT
oSer
ver
to network from network
inFr
omS
erve
r
inFr
omU
ser
keyboard monitor
Process
clientSocket
inputstream
inputstream
outputstream
TCPsocket
Clientprocess
client TCP socket
2: Application Layer 10
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
2: Application Layer 11
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 server
Createoutput stream
attached to socket
2: Application Layer 12
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
2: Application Layer 13
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 6789
Wait, on welcomingsocket for contact
by client
Create inputstream, attached
to socket
2: Application Layer 14
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
2: Application Layer 15
Socket programming: references
C-language tutorial (audio/slides): “Unix Network Programming” (J. Kurose),http://manic.cs.umass.edu/~amldemo/courseware/intro.
Java-tutorials: “All About Sockets” (Sun tutorial),
http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html
“Socket Programming in Java: a tutorial,” http://www.javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html
2: Application Layer 16
Chapter 2: Application layer
2.1 Principles of network applications 2.2 Web and HTTP 2.7 Socket programming with TCP 2.9 Building a Web server 2.3 FTP 2.4 Electronic Mail
SMTP, POP3, IMAP
2.5 DNS 2.6 P2P file sharing
2: Application Layer 17
HTTP overview
HTTP: 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
HTTP Nonpersistent and
Persistent (with or without pipelining)
Response time Message format
• Request and response
PC runningExplorer
Server running
Apache Webserver
Mac runningNavigator
HTTP request
HTTP request
HTTP response
HTTP response
2: Application Layer 18
http example (cont.)fetch www.someSchool.edu/someDepartment/home.index
1a. http client initiates TCP connection to http server (process) at www.SomeSchool.edu, port 80
2. http client sends http request message (containing URL) into TCP connection socket
1b. http server at host www.someSchool.edu waiting for TCP connection at port 80. “accepts” connection
3. http server receives request, forms response msg containing requested object (someDepartment/home.index), sends message into socket
time
(contains text, references to 10 jpeg images)
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
6. Steps 1-4(5) repeated for each of 10 jpeg objects
2: Application Layer 19
Building a simple Web server
handles one HTTP request
accepts the request parses header obtains requested file
from server’s file system
creates HTTP response message: header lines + file
sends response to client
after creating server, you can request file using a browser (eg IE explorer)
2: Application Layer 20
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
2: Application Layer 21
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
2: Application Layer 22
Building a simple Web server (cont’d) handles one HTTP request accepts the request import java.io.*; import java.net.*; import java.util.*;
class WebServer { public static void main(String argv[]) throws Exception { String requestMessageLine; String fileName;
ServerSocket ListenSocket = new ServerSocket(6789); Socket connectionSocket = ListenSocket.accept();
2: Application Layer 23
Building a simple Web server (cont’d) streams
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
requestMessageLine = inFromClient.readLine();
2: Application Layer 24
Building a simple Web server (cont’d) parses header
StringTokenizer tokenizedLine = New StringTokenizer (requestMeesageLine);
If (tokenizedLIne.nextToken().euals(“GET”)) {
2: Application Layer 25
Building a simple Web server (cont’d) obtains requested file from server’s file system
If (tokenizedLIne.nextToken().euals(“GET”)) {
fileName = tokenizedLine.nextToken();if (fileName.startsWith(“/”) == true )
fileName = fileName.substring(1);
File file = new File (fileName); int numOfBytes = (int) file.length(); FileInputStream inFile = new FileInputStream (fileName);
byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes);
2: Application Layer 26
Building a simple Web server (cont’d) creates HTTP response message: header lines sends response to client
outToClient.writeBytes(“HTTP/1.0 200 Document Follows\r\n”); if (fileName.endsWith(“.jpg”))
OutToClient.writeBytes(“Content-Type: image/jpeg\r\n”); if (fileName.endsWith(“.gif”))
OutToClient.writeBytes(“Content-Type: image/gif\r\n”);
OutToClient.writeBytes(“Content-Length: “ + numberOfBytes + “\r\n”);
OutToClient.writeBytes(“\r\n”);
2: Application Layer 27
Building a simple Web server (cont’d) creates HTTP response message: + file sends response to client after creating server, you can request file using
a browser
OutToClient.write(fileInBytes, 0, numberOfBytes);
connectionSocket.close(); } else System.out.println(“Bad Request Message”); }}
2: Application Layer 28
Project #1: Building a Multi-Threaded Web Server
a multi-threaded Web server: processing multiple simultaneous service requests in parallel.
Nonpersistent HTTP Processing real HTTP request and response
messages
Follow the instructions given Supply the missing code Test your server