Transcript Chapter2_2

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
 Misc
 About HW and project 1
 A quick demo of Apache
 Office hour cancelled
(02/12)
 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 2.6 P2P applications
2: Application Layer
1
Apache web server
 The most popular web server software

apache.org
 Download from
httpd.apache.org/download.cgi
 You can run your own web server!

Need to change port number in file httpd.conf
if installing it on department machines
 Write simple html pages
 Put images on the web
2: Application Layer
2
Socket programming
Goal: learn how to build client/server application that
communicate using sockets
Socket API
 introduced in BSD4.1 UNIX,
1981
 explicitly created, used,
released by apps
 client/server paradigm
 two types of transport
service via socket API:
 unreliable datagram
 reliable, byte streamoriented
socket
a host-local,
application-created,
OS-controlled interface
(a “door”) into which
application process can
both send and
receive messages to/from
another application
process
2: Application Layer
3
Socket-programming using TCP
Socket: a door between application process and endend-transport protocol (UCP or TCP)
TCP service: reliable transfer of bytes from one
process to another
controlled by
application
developer
controlled by
operating
system
process
process
socket
TCP with
buffers,
variables
host or
server
internet
socket
TCP with
buffers,
variables
controlled by
application
developer
controlled by
operating
system
host or
server
2: Application Layer
4
Socket programming with TCP
Client 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)
application viewpoint
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server
2: Application Layer
5
Client/server socket interaction: TCP
Server (running on hostid)
Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
TCP
wait for incoming
connection request connection
connectionSocket =
welcomeSocket.accept()
read request from
connectionSocket
write reply to
connectionSocket
close
connectionSocket
setup
create socket,
connect to hostid, port=x
clientSocket =
Socket()
send request using
clientSocket
read reply from
clientSocket
close
clientSocket
2: Application Layer
6
Stream jargon
keyboard
monitor
output
stream
inFromServer
Client
Process
process
input
stream
outToServer
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.
inFromUser
 A stream is a sequence of
input
stream
client
TCP
clientSocket
socket
to network
TCP
socket
from network
2: Application Layer
7
Socket programming with TCP
Client
Process
process
input
stream
output
stream
inFromServer
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)
outToServer
Example client-server app:
monitor
inFromUser
keyboard
input
stream
client
TCP
clientSocket
socket
to network
TCP
socket
from network
2: Application Layer
8
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception
{
String sentence;
String modifiedSentence;
Create
input stream
Create
client socket,
connect to server
Create
output stream
attached to socket
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());
2: Application Layer
9
Example: Java client (TCP), cont.
Create
input stream
attached to socket
BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
Send line
to server
outToServer.writeBytes(sentence + '\n');
Read line
from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
2: Application Layer
10
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
Create
welcoming socket
at port 6789
Wait, on welcoming
socket for contact
by client
Create input
stream, attached
to socket
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()));
2: Application Layer
11
Example: Java server (TCP), cont
Create output
stream, attached
to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket
clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
Write out line
to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
End of while loop,
loop back and wait for
another client connection
2: Application Layer
12
Chapter 2: Application layer
 2.1 Principles of
network applications
 2.2 Web and HTTP
 2.3 FTP
 2.4 Electronic Mail

 2.7 Socket programming
with TCP
 2.8 Socket programming
with UDP
 Threads
SMTP, POP3, IMAP
 2.5 DNS
 2.6 P2P applications
2: Application Layer
13
Socket programming with UDP
UDP: no “connection” between
client and server
 no handshaking
 sender explicitly attaches
IP address and port of
destination to each packet
 server must extract IP
address, port of sender
from received packet
application viewpoint
UDP provides unreliable transfer
of groups of bytes (“datagrams”)
between client and server
UDP: transmitted data may be
received out of order, or
lost
2: Application Layer
14
Client/server socket interaction: UDP
Server
(running on hostid)
create socket,
port= x.
serverSocket =
DatagramSocket()
read datagram from
serverSocket
write reply to
serverSocket
specifying
client address,
port number
Client
create socket,
clientSocket =
DatagramSocket()
Create datagram with server IP and
port=x; send datagram via
clientSocket
read datagram from
clientSocket
close
clientSocket
2: Application Layer
15
Example: Java client (UDP)
input
stream
Client
process
monitor
inFromUser
keyboard
Process
Input: receives
packet (recall
thatTCP received
“byte stream”)
UDP
packet
receivePacket
packet (recall
that TCP sent
“byte stream”)
sendPacket
Output: sends
UDP
packet
client
UDP
clientSocket
socket
to network
UDP
socket
from network
2: Application Layer
16
Example: Java client (UDP)
import java.io.*;
import java.net.*;
Create
input stream
Create
client socket
Translate
hostname to IP
address using DNS
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();
2: Application Layer
17
Example: Java client (UDP), cont.
Create datagram
with data-to-send,
length, IP addr, port
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
Send datagram
to server
clientSocket.send(sendPacket);
Read datagram
from server
clientSocket.receive(receivePacket);
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
2: Application Layer
18
Example: Java server (UDP)
import java.io.*;
import java.net.*;
Create
datagram socket
at port 9876
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)
{
Create space for
received datagram
Receive
datagram
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
2: Application Layer
19
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of
sender
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
Create datagram
to send to client
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out
datagram
to socket
serverSocket.send(sendPacket);
}
}
}
End of while loop,
loop back and wait for
another datagram
2: Application Layer
20
Threads
 References
MODERN OPERATING SYSTEMS (SECOND
EDITION) by Andrew S. Tanenbaum
 Operating System Concepts by Silberschatz,
Galvin, and Gagne. Sixth edition

2: Application Layer
21
Threads
 Thread is used to support concurrent execution
 A program may need to support simultaneously
 the user interaction
 the network communication
 Many software packages running on PCs are
multithreaded


E.g., in a word processor, a thread for spell checking, a
thread for displaying graphics, a thread for reading
keystrokes from the user
E.g., web servers need to support many connections at
once that allows each client independent service
2: Application Layer
22
Thread is lightweight
 A thread sometimes is called a lightweight
process
Code, Data, Files
Registers, stacks
Code, Data, Files
Registers
stacks
Registers Registers
stacks
stacks
Thread
Single-threaded process
Multithreaded process
2: Application Layer
23
Benefits of multithreaded
programming
 Responsiveness


Allows a program to continue running while part of it is
performing a lengthy operation
E.g., web browser allows user interaction while loading an image
 Resource sharing

Threads share the memory and resources of the process to
which they belong
 Economy


It is more time-consuming to create and manage processes than
threads
In Solaris 2, creating a process is 30 times slower than creating
a thread
 Utilization of multiprocessor architectures

A single-threaded process can only run on one CPU even if there
are multiple CPU available
2: Application Layer
24
Threads in Java
 Java Thread API
 http://java.sun.com/j2se/1.3/docs/api/java/lang/Th
read.html
 public class Thread extends Object implements
Runnable
 Usage
 Create a class that extends Thread - OR –
implements Runnable
• Must implement the run method
Instantiate this class - OR - a Thread to run this
Runnable
 Invoking run method starts a new execution path

2: Application Layer
25
Example: PrimeThread
class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime . . .
}
}
2: Application Layer
26
Example: to run the thread
PrimeThread p = new PrimeThread(143);
p.start();
2: Application Layer
27
Example: PrimeRun
class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}
public void run() {
// compute primes larger than minPrime . . .
}
}
2: Application Layer
28
Example: to run the thread
PrimeRun p = new PrimeRun(143);
new Thread(p).start();
-------------------------------------------Recall this constructor of class Thread
Thread(Runnable p)
Allocates a new Thread object.
2: Application Layer
29
Threads in Java, yet another example
Class Channel extends Thread {
Channel(...) { // constructor
}
public void run() {
/* Do work here */
}
}
/* other code to start thread */
Channel C = new Channel(); // constructor
C.start(); // start new thread in run method
C.join(); // wait for C’s thread to finish.
2: Application Layer
30
Threads in Java
 After start(), a new thread is created and
method run() is executed by the new
thread
 Calling join() method waits for the run
method to terminate
2: Application Layer
31
Threads in web servers
 Server main thread waits for client requests
 After accept() method, main thread creates a new
worker thread to handle this specific socket
connection
 Main thread returns to accept new connections
 Worker thread handles this request, provides
logical independent service for each client
2: Application Layer
32
Synchronized method
 Can add keyword synchronized to a method
 Result: at most 1 thread can execute the
method at a time
 Used for altering data structures shared
by threads

Be careful! No operations should block in the
synchronized method or program can get stuck.
2: Application Layer
33
Exercise
 Make your TCP server multi-threaded
2: Application Layer
34
Slides credits
 J.F Kurose and K.W. Ross
 Richard Martin
2: Application Layer
35