Download as pdf or txt
Download as pdf or txt
You are on page 1of 99

Chapter - 2

Advanced Networks Congestion


control Algorithms and Protocols
Outline
 Transport-layer services
 UDP
 TCP: Connection-oriented transport
 segment structure
 reliable data transfer
 flow control
 connection management
 congestion control

 TCP and High speed networks


 Socket Programming using TCP

2
Internet Protocol (IP)

 Packets may get delivered out-of-order

 Packets may be lost

 Packets may be duplicated

 Works on best effort

3
Transport services and protocols
 provide logical communication application
transport
between app processes running network
data link
on different hosts physical
network
data link
network physical
 transport protocols run in end data link
physical
systems network
data link
 sender side: breaks app physical network
data link
messages into segments, physical

passes to network layer network


data link
physical
 rcver side: reassembles
segments into messages, application
transport
passes to app layer network
data link
 more than one transport physical

protocol available to apps


 Internet: TCP and UDP

4
Internet transport-layer protocols
 Two end-to-end transport protocols

 TCP - Transmission Control Protocol


 a reliable connection-oriented protocol that allows a byte stream to
be delivered without error
 handles flow control to make sure that a fast sender does not
swamp a slow receiver
 UDP - User Datagram Protocol
 an unreliable, connectionless protocol
 for applications that do not want TCP’s sequencing or flow control
and wish to provide their own

5
Internet transport protocols services

TCP service: UDP service:


 connection-oriented: setup  unreliable data transfer
required between client and between sending and
server processes receiving process
 reliable transport between  no connection setup,
sending and receiving process  Un reliable,
 flow control: sender won’t  no flow control,
overwhelm receiver  no congestion control,
 congestion control: sender  no timing,
doesn’t overrun the resources
 no throughput
of the network
guarantee, or
 Error control: uses check sum
 no security
method
 In-order delivery of data or
segments 6
How demultiplexing works?
 host receives IP datagrams
 each datagram has source 32 bits
IP address, destination IP
address source port # dest port #

 each datagram carries 1


transport-layer segment other header fields
 each segment has source,
destination port numbers
(16 bits). application
(recall: well-known port data
numbers reserved for (message)
specific applications)

 host uses IP addresses & port


numbers to direct segment to TCP/UDP segment format
appropriate socket
7
Connectionless demultiplexing
 Create a socket with port
number  When host receives UDP
DatagramSocket mySocket1 = segment:
new DatagramSocket(9157);  checks destination port
DatagramSocket mySocket2 = number in segment
new DatagramSocket(5775);  directs UDP segment to
socket with that port number
 Create datagram with data-to-
send, length, IP addr, port
 IP datagrams with different
DatagramPacket sendPacket =
new source IP addresses and/or
DatagramPacket(sendData, source port numbers
sendData.length, IPAddress,
6428);
directed to same socket
 UDP socket identified by a
two-tuple:

(dest IP address, dest port


number)

8
Connectionless demultiplexing…
DatagramSocket serverSocket =
new DatagramSocket(6428);
9157 6428 5775
P3 P1
P2
P1

SP: 6428 SP: 6428


DP: 9157 DP: 5775
IPs, data IPs, data
SP: 9157 SP: 5775
client DP: 6428 DP: 6428 Client
server
IP: A IPs, data IPs, data IP:B
IP: C

9
Connection-oriented demux
 TCP socket identified by  Server host may support
4-tuple: many simultaneous TCP
 source IP address sockets:
 source port number  each socket identified by its
 dest IP address own 4-tuple
 dest port number  Web servers have
 receiver host uses all different sockets for each
four values to direct connecting client
segment to appropriate
socket

10
Connection-oriented demux…

P1 P4 P5 P6 P2 P1P3

SP: 5775
DP: 80
S-IP: B
D-IP:C

SP: 9157 SP: 9157


client DP: 80 DP: 80 Client
server
IP: A S-IP: A
IP: C S-IP: B IP:B
D-IP: C D-IP: C

11
Connection-oriented demux:
Threaded Web Server

P1 P4 P2 P1P3

SP: 5775
DP: 80
S-IP: B
D-IP:C

SP: 9157 SP: 9157


client DP: 80 DP: 80 Client
server
IP: A S-IP: A
IP: C S-IP: B IP:B
D-IP:C D-IP:C

12
Connectionless vs connection-oriented

Some Instructor Process

Mailbox(es) Socket(s)

Some Instructor’s name Port #

AAIT, ECE IP addr.

Connectionless: all mails to the same mailbox


Connection-oriented: one mailbox for mails to HOD,
another for mails to secretary,…
13
UDP: User Datagram Protocol [RFC 768]
 UDP is “best effort” service as
UDP segments may be:
 lost
Why is there a UDP?
 delivered out of order
 no connection establishment
 connectionless: (which can add delay)
 no handshaking between  simple: no connection state
UDP sender, receiver at sender, receiver
 each UDP segment handled  small segment header
independently of others  no congestion control: UDP
 e.g., DNS can use UDP, give can blast away as fast as
me the IP address of the desired
host name
www.google.com

 process with internal flow and error control mechanisms,


e.g., TFTP (Trivial FTP) 14
UDP: more
 often used for streaming
32 bits
multimedia apps
Length, in source port # dest port #
 loss tolerant
bytes of UDP length checksum
 rate sensitive segment,
 other UDP uses including
header
 DNS
 SNMP
Application
 reliable transfer over UDP: data
 add reliability at application (message)
layer
 application-specific error
recovery! TFTP UDP segment format

15
 some of the well-known ports used by UDP (see www.iana.org for
a complete list)
Port Protocol Description
7 Echo Echoes a received datagram back to the sender
9 Discard Discards any datagram that is received
11 Users Active users
13 Daytime Returns the date and the time
17 Quote Returns a quote of the day
19 Chargen Returns a string of characters
53 DNS Domain Name Service
67 Bootps Server port to download bootstrap information
68 Bootpc Client port to download bootstrap information
69 TFTP Trivial File Transfer Protocol
111 RPC Remote Procedure Call
123 NTP Network Time Protocol
161 SNMP Simple Network Management Protocol
162 SNMP Simple Network Management Protocol (trap)
16
Transmission Control Protocol (TCP)

 Reliable ordered delivery


 Implements congestion avoidance and control
 Reliability achieved by means of
retransmissions if necessary
 End-to-end semantics
 Acknowledgements sent to TCP sender confirm
delivery of data received by TCP receiver
 Ack for data sent only after data has reached
receiver

17
Window Based Flow Control
 Sliding window protocol
 Window size minimum of
 receiver’s advertised window - determined by
available buffer space at the receiver
 congestion window - determined by the sender,
based on feedback from the network

Sender’s window

1 2 3 4 5 6 7 8 9 10 11 12 13

Acks received Not transmitted

18
Window Based Flow Control

Sender’s window

1 2 3 4 5 6 7 8 9 10 11 12 13

Ack 5

1 2 3 4 5 6 7 8 9 10 11 12 13

Sender’s window
19
TCP: Overview RFCs: 793, 1122, 1323, 2018, 2581

 full duplex data:


 point-to-point:  bi-directional data flow in
 one sender, one receiver same connection
 reliable, in-order byte  connection-oriented:
stream:  handshaking (exchange of
 no “message boundaries” control msgs) init’s
sender, receiver state
 pipelined:
before data exchange
 TCP congestion and flow
control set window size  flow control:
 sender will not overwhelm
 send & receive buffers
receiver
 Congestion control:
application application
writes data reads data
socket socket
door
 sender doesn’t overrun
door
TCP TCP
send buffer receive buffer
segment the network resource
20
Overview
TCP overview(cont)
 TCP: Tahoe, Reno, New-Reno,Sack,
Vegas, Westwood,…
 Sending rate is controlled by
 Congestion window (cwnd): limits the
# of packets in flight
 Slow-start threshold (ssthresh): when
CA start
 Loss detection
 3 duplicate ACKs (faster, more efficient)
 Retransmission timer expires (slower,
less efficient)
 Overview of congestion control mechanisms
 Slow-start phase: cwnd start from 1
and increase exponentially
 Congestion avoidance (CA): increase
linearly Slow-start Congestion
avoidance
 Fast retransmit and fast recovery:
Trigger by 3 duplicate ACKs
21
TCP segment structure
32 bits
URG: urgent data counting
(generally not used) source port # dest port #
by bytes
sequence number of data
ACK: ACK #
valid acknowledgement number (not segments!)
head not
PSH: push data now len used
UA P R S F Receive window
(generally not used) # bytes
checksum Urg data pnter
rcvr willing
RST, SYN, FIN: to accept
Options (variable length)
connection estab
(setup, teardown
commands)
application
Internet data
checksum (variable length)
(as in UDP)

22
TCP seq. #’s and ACKs
Seq. #’s: Host A Host B
 byte stream User
“number” of first types
byte in segment’s ‘C’
host ACKs
data receipt of
‘C’, echoes
ACKs:
back ‘C’
 seq # of next byte
expected from other
host ACKs
side receipt
 cumulative ACK of echoed
‘C’
Q: how receiver handles
out-of-order segments
 A: TCP spec doesn’t time
say, - up to
implementor
23
TCP Round Trip Time and Timeout
Q: how to set TCP Q: how to estimate RTT?
timeout value?
 SampleRTT: measured time
 It should be longer from segment transmission
than RTT until ACK receipt
 If too short:  ignore retransmissions
premature timeout  SampleRTT will vary
• unnecessary
 Average of several recent
retransmissions
measurements, not just
 If too long:
current SampleRTT
slow reaction to
segment loss

24
Retransmission Time Out (RTO) estimation
 Until an RTT measurement has been made for a segment
sent, the TCP sender should set RTO to three seconds
(G).
 When the first RTT measurement R is made, the sender
must set:
SRTT = R, and RTTVAR = R/2
RTO = SRTT + max (G, K · RTTVAR), where K = 4
 When a subsequent RTT measurement R’ is made, the
sender must update the variables as follows:
RTTVAR = (1 −β) · RTTVAR + β · |SRTT − R’ |
SRTT = (1 − α) · SRTT + α · R’

α and β are normally set to 1/8 and 1/4, respectively


25
TCP Connection Management
Recall: TCP sender, receiver Three way handshake:
establish “connection” before
exchanging data segments Step 1: client host sends TCP SYN
 initialize TCP variables: segment to server
 specifies initial seq #
 seq. #s
 no data
 buffers, flow control info
(e.g. RcvWindow) Step 2: server host receives SYN,
 client: connection initiator replies with SYNACK segment
Socket clientSocket = new
Socket("hostname","port
 server allocates buffers
 specifies server initial seq.
number");
#
 server: contacted by client
ServerSocket servSock=new
Step 3: client receives SYNACK,
ServerSocket("port no"); replies with ACK segment,
Socket link= which may contain data
servSock.accept();

26
TCP Three phase handshaking:
connection establishment

client server

send SYN seq=x

receive SYN seq=x


send SYN seq=y,
ACK ack x+1

receive SYN +ACK seq=y

send ACK
ack=y+1

27
TCP Connection Management (cont.)

Closing a connection: client server

close
client closes socket:
clientSocket.close();
close
Step 1: client sends TCP FIN
control segment to server

timed wait
Step 2: server receives FIN,
replies with ACK. Closes
connection, sends FIN.
closed

28
TCP Connection Management (cont.)

Step 3: client receives FIN, client server


replies with ACK. closing
 Enters “timed wait” - will
respond with ACK to
received FINs
closing
Step 4: server, receives ACK.
Connection closed.

timed wait closed

closed

29
TCP reliable data transfer
 TCP creates rdt service  At the sender side:
on top of IP’s unreliable  Reception of 3 DUPACKs
service mean, network is
 Uses sliding window congested. (Sender enters
protocol fast recovery and fast
 Cumulative acks retransmission phases)
 TCP uses single  Expiration of RTO means,
retransmission timer network is severely
 Retransmissions are congested.(Sender enters to
triggered by: slow start phase)
 Timeout (RTO) events
 Three duplicate acks

30
Flow and congestion control
 TCP is a window-based flow and congestion
control protocol.

 It uses sliding window mechanism to manage its


data transmission.

 The sending rate of a TCP connection is


regulated by two distinct mechanisms:
 Flow control and
 Congestion control.

31
Flow and congestion control

Flow control Congestion control


 Used to avoid that a  It is mainly dealt with the
TCP sender doesn’t traffic inside the network.
overflows the receiver’s  Its purpose is to prevent
buffer. collapse inside the
 The receiver advertises network when the sender
in every ACK is faster than the network
transmitted a window in forwarding
limit to the sender. data.(CWND).
(AWND).

32
Connection control
 The TCP sender is Note
limited by both AWND  AWND is used to prevent
and CWND. the sender from
 The sending window overrunning the
size of the sender is resources of the receiver.
taken as being the  CWND is to prevent the
minimum of the AWND sender from sending
and the CWND. more data than the
network can
W = min (CWND, AWND) accommodate in the
current load conditions.

33
Principles of Congestion Control
Congestion:
 informally: “too many sources sending too much data
too fast for network to handle”
 different from flow control
 manifestations:
 lost packets (buffer overflow at routers)
 long delays (queuing in router buffers)

34
TCP’s Congestion Control mechanisms
 Has four phases:

 Slow start,
 Congestion
avoidance,
 Fast retransmit and
 Fast recovery.

Congestion
Slow start
avoidance

35
TCP Slow Start

 When connection begins, CongWin = 1 MSS


 available bandwidth may be >> MSS/RTT
 desirable to quickly ramp up to respectable rate

 When connection begins, increase rate exponentially


fast until first loss event

36
TCP Slow Start (more)

 When connection Host A Host B


begins, increase rate
exponentially until first

RTT
loss event:
 double CongWin every
RTT
 done by incrementing
CongWin for every ACK
received
 Summary: initial rate is
slow but ramps up
exponentially fast time

37
Congestion avoidance phase
TCP S TCP R

 cwnd will increase by


PKT 1 one if there is no
PKT 2 packet loss
cwnd = w = 4 ACK 2
PKT 3
ACK 3
PKT 4
ACK 4  After receiving all
cwnd ACKs,
ACK 5
cwnd + 1/cwnd PKT 5 cwnd = cwnd +1
cwnd + 2/cwnd PKT 6
cwnd + 3/cwnd
In the code:
PKT 7
cwnd =cwnd + MSS*MSS
cwnd + cwnd/cwnd PKT 8
= cwnd +1 cwnd
PKT 9
Exponential Backoff
 Double RTO on each timeout

T1 T2 = 2 * T1

Timeout interval doubled


Packet
transmitted

Time-out occurs
before ack received,
packet retransmitted

39
Detecting Packet Loss Using Dupacks:
Fast Retransmit Mechanism
 Dupacks may be generated due to
 packet loss, or
 out-of-order packet delivery

 TCP sender assumes that a packet loss has


occurred if it receives three dupacks
consecutively
12 11 10 9 8 7

Receipt of packets 9, 10 and 11 will each generate


a dupack from the receiver. The sender, on getting
these dupacks, will retransmit packet 8.
40
Congestion control: inferring loss
 After 3 dup ACKs:
 CongWin is cut in half Philosophy:
 window then grows
linearly  3 dup ACKs indicates
 But after timeout event: network capable of
delivering some segments
 CongWin instead set to
 timeout indicates a
1 MSS;
“more alarming”
 window then grows congestion scenario
exponentially
 to a threshold, then
grows linearly

41
TCP congestion control algorithm:
Example
Given:
• MSS (Maximum Segment Size) = 1024 byte
• Initially congestion window size(CWND)= 1kbyte at time 0
• The CWND then grows exponentially till it reaches the
threshold (16kbyte). (Slow start)
• Starting then, it grows linearly (congestion avoidance ) till it
reaches to 24 Kbyte. (Packet loss detected)
• At time 9, a timeout occurs.

Find: the values of threshold and CWND? And


show the rest of the process.

42
TCP’s Congestion Control alg: Expiration of RTO

24
22
Congestion window size (CWND)

20
18 threshold
16
14 threshold
12
10
8
6
4
2
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Time 43
TCP’s Congestion Control alg: 3 DUPACKs

24
22
Congestion window size (CWND)

20
18 threshold
16
14
threshold
12
10
8
6
4
2
0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Time 44
TCP and High Speed Networks
 High Speed Networks (HSN) with the most up-to-date
networking technologies are currently being deployed to
support
 a large variety of new scientific applications.
 an increasing demand for high-speed Internet access and
bandwidth consuming applications.

 The TCP congestion control algorithm has been successful


in handling low to medium speed networks
 Kbps to several Mbps
 The challenge now is to make TCP operational and efficient
on these new high-speed network infrastructures.
 tens of Mbps to Gbps and Gbps to Tbps
45
TCP and High Speed Networks

 TCP performs very well in low to middle speed


networks

 However, it has very poor performance in high


speed networks,
 as TCP is very inefficient in utilizing the high-
speed network bandwidth.

46
High-Speed Applications

High-Speed Applications
Weather Simulation Video Conference Telemedicine

Transport Protocols
be able to transfer a large amount of data
over a long distance within a short amount of time

High-Speed Networks
47
What is High Speed TCP?
 Changes the way TCP behaves at high speed
 (ie large cwnd)

 Standard TCP has two modes


 Slow start (not very slow…)
 Congestion Avoidance

 Focuses on Congestion Avoidance Mode

 BUT only when we are at high speeds, else do what


normal Standard TCP does…
Why high-speed TCP?
 Motivation
 10Gb/s links now common in Internet core
 Some users have access to and need for 10Gb/s
end-to-end
• e.g., very large scientific, financial databases
 Problems
 slow start
 Additive increase, multiplicative decrease (AIMD)

49
Why high-speed TCP?
 The problem is that TCP increases its rate too slowly,
and decreases it too fast.
 High-speed TCP algorithms tried to get around this
problem.
 Goals of high-speed TCPs
 Rapidly increase the data rate and maintain a high data
rate.
 Be fair with normal TCP (e.g. RENO)
• This is especially required when sharing congested links.
• We cannot have two protocol stacks, one for congested
networks and one for uncongested networks.
 Designed as minimal change to TCP to allow use of
high-bandwidth paths.
50
TCP Congestion Control
 The instantaneous throughput of TCP is controlled by a variable cwnd,
 TCP transmits approximately a cwnd number of packets per RTT
(Round-Trip Time).

cwnd = cwnd + 1 cwnd = cwnd * (1-1/2)

Packet loss Packet loss Packet loss Packet loss TCP


cwnd

Slow start Congestion avoidance Time (RTT)


51
Standard TCP
 TCP uses two parameters during Congestion Avoidance -
AIMD(a,b)
 Increase parameter, a
 Decrease parameter, b

 Standard TCP uses


 a=1
 b=0.5
 High Speed TCP introduces a dependence of a and b
depending on the current cwnd
 a->a(cwnd)
 b->b(cwnd)
 If we increase a more with larger cwnd we can get back up to
our ‘optimal’ cwnd size for the network path
 If we decrease b less we don’t lose as much bandwidth due to a
small congestion window
Standard TCP
 Window size recovers slowly to packet loss in High-Speed
Network

1.4 hours 1.4 hours 1.4 hours


slow
Packet lossincrease
Packet loss Packet loss Packet loss TCP
cwnd 100,000 10Gbps
fast
decrease

50,000 cwnd = cwnd cwnd = cwnd *


5Gbps
+1 0.5

Slow start Congestion avoidance Time (RTT)

53
Response Function of TCP
 Response function of TCP is the average throughput of a TCP
connection in terms of the packet loss probability, the packet size,
and the round-trip time.

 Response Function of TCP is :


MSS 1.2
R
RTT p 0.5
 R : Average Throughput
 MSS: Packet Size
 RTT: Round-Trip Time
 P : Packet Loss Probability

54
Proposed High-Speed Protocols
 Window-Based Protocols
 AIMD (Additive Increase Multiplicative Decrease)
• Jumbo Frame, GridFTP, PFTP, PSockets
 HSTCP (High-Speed TCP) by Sally Floyd at ICIR, Berkeley
 STCP (Scalable TCP) by Tom Kelly at Cambridge University
 FAST (Fast AQM Scalable TCP) by Steven Low at California
Institute of Technology

 Rate-Based Protocols
 SABUL (Simple Available Bandwidth Utilization Library ) by
Robert Grossman at University of Illinois at Chicago

window-based protocols are known for safer incremental deployment.


D. Bansal, H. Balakrishnan, S. Floyd, and S. Shenker, "Dynamic behavior of slowly
responsive congestion controls", In Proceedings of SIGCOMM 2001, San Diego,
California.
55
AIMD (Additive Increase Multiplicative Decrease)
 AIMD increases cwnd by a larger number, say 32, instead of 1 per
RTT.
 After a packet loss, AIMD decreases cwnd by 1/8, instead of 1/2

cwnd = cwnd + 1 cwnd = cwnd * (1-1/2)

cwnd = cwnd + 32 cwnd = cwnd * (1-1/8)

Packet loss Packet loss Packet loss Packet loss TCP


cwnd

Slow start Congestion avoidance Time (RTT)


56
Response Function of AIMD
• The response function of
MSS 1.2
 TCP: R AIMD is very similar to that
RTT p 0.5
of the TCP.
•The only difference is the
 AIMD: R 
MSS 15.5 constant.
RTT p 0.5 •The constant of TCP is 1.2,
and the constant of AIMD is
The throughput of AIMD is 15.5.
always about 13 times •Therefore, the throughput of
larger than that of TCP AIMD is always about 13
times larger than the
throughput of TCP.

57
Scalable TCP
• Very simple modifications to TCP algorithms.
• For cwnd  lwnd, use the traditional window update
algorithm.
• For cwnd > lwnd,
• Increase Function : for each ack, cwnd = cwnd +
[0.01 * cwnd]
• Decrease Function : for each loss, cwnd = cwnd -
0.125 * cwnd
• lwnd chosen to be 16 corresponding to the drop
probability of 5.86 * 10-3
• This response function is effectively MIMD.

58
STCP (Scalable TCP)
 STCP adaptively increases cwnd, and decreases cwnd by 1/8.

cwnd = cwnd + 1 cwnd = cwnd * (1-1/2)

cwnd = cwnd + 0.01*cwnd cwnd = cwnd * (1-1/8)

Packet loss Packet loss Packet loss Packet loss TCP


cwnd

Slow start Congestion avoidance Time (RTT)


59
HSTCP (High Speed TCP)
 HSTCP adaptively increases cwnd, and adaptively decreases cwnd.
 The larger the cwnd, the larger the increment, and the smaller the
decrement.

cwnd = cwnd + 1 cwnd = cwnd * (1-1/2)

cwnd = cwnd + inc(cwnd) cwnd = cwnd * (1-dec(cwnd))

Packet loss Packet loss Packet loss Packet loss TCP


cwnd

Slow start Congestion avoidance Time (RTT)


60
Response Functions of HSTCP and STCP
MSS 0.12
 HSTCP: R 
RTT p 0.835
Packet Drop Congestion RTTs Between Packet Drop Congestion RTTs Between
Rate P Window W Losses Rate P Window W Losses
10-2
12 8 10-2 12 8
10-3
38 25 10-3 38 25
10-4
120 80 10-4 263 38
10-5
379 252 10-5 1795 57
10-6
1200 800 10-6 12279 83
10-7
3795 2530 10-7 83981 123
10-8
12000 8000 10-8 574356 180
10-9
37948 25298 10-9 3928088 264
10-10
120000 80000 10-10 26864653 388

TCP Response Function for Standard TCP TCP Response Function for Highspeed TCP

 STCP: R  MSS 0.08


RTT p

61
BIC (Binary Increase Congestion control)

 Similar to other high-speed protocols, BIC also


modifies the increase and decrease part of congestion
avoidance of TCP.
 In Bic, the increase depends not only the current
window size cwnd, but also depends on some history
information.
 The decrease part of BIC is the same as AIMD and
STCP.
 After a packet loss, cwnd is decreased by 1/8.

62
BIC (Binary Increase Congestion control)
 BIC adaptively increase cwnd, and decrease cwnd by 1/8

cwnd = cwnd + 1 cwnd = cwnd * (1-1/2)

cwnd = cwnd + f(cwnd, history) cwnd = cwnd * (1-1/8)

Packet loss Packet loss Packet loss Packet loss TCP


cwnd

Slow start Congestion avoidance Time (RTT)


63
BIC (Binary Increase Congestion control)

 The increase part of congestion avoidance – a connection


looks for the available bandwidth by comparing:
• its current throughput with
• the available bandwidth,
• and adjusting cwnd accordingly.

 Response Function of BIC


MSS 2.7 S max
on high-speed networks R
RTT p 0.5

64
Processes Communication Using Socket

Process: program running


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
communication (defined by
contacted
OS).
• processes in different
hosts communicate by
exchanging messages

65
Elements of Client-Server
Computing/Communication
a client, a server, and network

network

client
server

• Processes follow protocols that define a set of rules that must be observed
by participants:
– How the data exchange is encoded?
– How events (sending, receiving) are synchronized (ordered) so that participants
66 can send and receive data in a coordinated manner?
Sockets
• process sends/receives host or
client
host or
server
messages to/from its socket
• socket analogous to door
controlled by
app developer
process process
– sending process gives message
out door socket socket
TCP with TCP with
– sending process relies on Internet buffers,
buffers,
transport infrastructure on variables variables
other side of door which brings
message to socket at receiving
process controlled
by OS

67
Addressing processes
• to receive messages, • identifier includes both IP
process must have address and port numbers
identifier associated with process on
• host device has unique host.
32-bit IP address • Example port numbers:
• Q: does IP address of – HTTP server: 80
host on which process – Mail server: 25
runs suffice for identifying
• to send HTTP message to a
the process?
web server with IP
– A: No, many processes address:217.110.45.12, we
can be running on same use:
host

– 217.110.45.12:80 68
Socket Addresses

 process-to-process  a transport-layer protocol needs a


delivery needs two pair of socket addresses:
addresses:  the client socket address and
 IP address and  the server socket address
 port number at
each end  the IP header contains the IP
address; the UDP or TCP header
 the combination of an IP contains the port number
address and a port
number is called a socket
address

69
Some of the well-known ports used by TCP and UDP
Port Protocol Description
7 Echo Echoes a received datagram back to the sender
9 Discard Discards any datagram that is received
11 Users Active users
13 Daytime Returns the date and the time
17 Quote Returns a quote of the day
19 Chargen Returns a string of characters
20 FTP, Data File Transfer Protocol (data connection)
21 FTP, Control File Transfer Protocol (control connection)
23 TELNET Terminal Network
25 SMTP Simple Mail Transfer Protocol
53 DNS Domain Name Server
67 BOOTP Bootstrap Protocol
79 Finger Lookup information about a user
80 HTTP Hypertext Transfer Protocol
111 70 RPC Remote Procedure Call
Java Sockets Java’s .net package
provides two classes:
Server ServerSocket(1234) Socket – for
implementing a client

ServerSocket – for
implementing a server

Output/write stream Client

Input/read stream

Socket(“128.250.22.134”, 1234)
71
It can be host_name like “hen.aait.edu.et”
Socket programming
Goal: learn how to build client/server application that communicate using
sockets

Socket API
socket
• introduced in BSD4.1 UNIX,
1981 a host-local,
application-created,
• explicitly created, used, released OS-controlled interface (a
by apps “door”) into which
• client/server paradigm application process can
both send and
• two types of transport service receive messages to/from
via socket API: another application process
– reliable, byte stream-oriented
TCP
– unreliable datagram UDP
72
Socket programming using TCP
Client must contact server
• server process must first be running
• server must create 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
73
Client/server socket interaction: TCP

Server Client
(running on hostid)
create socket,
port=x, for
incoming request:
ServerSocket servSock =new
ServerSocket(x)

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
Socket link = Socket clientSocket = new
servSock.accept() Socket(h,x)

send request using


read request from clientSocket
servSock

write reply to
servSock read reply from
clientSocket
close
servSock
close
clientSocket 74
Stream terminology
keyboard monitor

• A stream is a sequence of
characters that flow into or out

inFromUser
of a process. input
stream

Client
Process
process
• An input stream is attached to
some input source for the
process, e.g., keyboard or
socket.

inFromServer
outToServer
output input
stream stream

• An output stream is attached to


an output source, e.g., monitor client TCP
clientSocket
or socket. socket TCP
socket

to network from network

75
Introducing the java.net Package

76
Main classes in java.net

77
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
DataOutputStream os;
DataInputStream is;
server = new ServerSocket(PORT);
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream(
client.getInputStream() );
os = new DataOutputStream(
client.getOutputStream() );
4. Perform communication with client
Receive from client: String line =
is.readLine();
Send to client: os.println("Hello\n");
5. Close sockets: 78
client.close();
Implementing a Server
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter
(the thread creates streams (as in step (3) and does
communication as stated in (4).
Remove thread once service is provided.
}
79
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
– Receive data from the server:
String line = is.readLine();
– Send data to the server:
os.println("Hello\n");
4. Close the socket when done:
client.close(); 80
Server-Socket programming
• The java.net package provides ServerSocket and
DatagramSocket objects for servers at the TCP/IP
socket level.

Establishing a stream server involves five steps:


1- Create a new Socket with port number.
2- Set a Socket connect for a client using the accept() method.
3- Create inputstream and outputstream objects.
4- Process stream data.
5- Close the streams.
81
Server-Socket programming cont’d…
 The server program establishes a socket connection
on Port 1234 in its listenSocket method.
 It reads data sent to it and sends that same data
back to the client in its listenSocket method.

ListenSocket Method
 The listenSocket method creates a ServerSocket
object with port number on which the server
program is going to listen for client
communications.
82
Server-Socket Programming cont’d…

 The port number must be an available port, which means the


number cannot be reserved or already in use.
 For example, Unix systems reserve ports 1 through 1023 for
administrative functions leaving port numbers greater than
1024 available for use.
public static void listenSocket(){
try {
ServerSocket servSock = new ServerSocket(1234);
}
catch(IOException e){
System.out.println("Unable to create port!");
System.exit(-1);
}
83
Server-Socket Programming cont’d…
 Next, the listenSocket method creates a Socket connection
for the requesting client.

 This code executes when a client starts up and requests the


connection on the host and port where this server program
is running.

 When the connection successfully established, the


servSock.accept() method returns a new Socket object.

84
Server-Socket Programming cont’d…

Socket link=null;
try
{
link = servSock.accept();
}
catch(IOException e)
{
System.out.println("Accept failed: 1234");
}

85
Server-Socket Programming cont’d…

 Then, the listenSocket method creates a BufferedReader


object to read the data sent over the socket connection from
the client program.
 It also creates a PrintWriter object to send the data received
back to the client.

BufferedReader in = new BufferedReader(new


InputStreamReader(link.getInputStream()));

PrintWriter out = new


PrintWriter(link.getOutputStream(), true);

86
Server-Socket Programming cont’d…
 Lastly, the listenSocket method loops on the input stream to
read data as it comes in from the client and writes to the output
stream to send the data back.

int numMessages = 0;
String message = in.readLine();
while (!message.equals("close")) {
System.out.println("Message received.");
numMessages++;
out.println("Message " + numMessages + ": " +
message);
message = in.readLine();
}

87
Lab: Server -Socket source code
import java.io.*;
import java.net.*;
public class Server {
private static ServerSocket servSock;
private static final int PORT=1234;
public static void main(String[] args)
throws IOException {
System.out.println("Openning port.....");
while(true)
{
listenSocket();
}
}
88
Lab: Server-Socket source code …
public static void listenSocket() {
try {
Create servSock=new ServerSocket(PORT);
server socket
at port 1234 } catch(IOException e) {
System.out.println("Unable to create
socket with port no:1234!");
System.exit(-1); }
Socket link=null;
try {
Create socket
connection
link=servSock.accept();
with the client } catch(IOException e){
System.out.println("Accept failed:
Port 1234");
89
}
Lab: Server-Socket source code …
try {
Create input BufferedReader in=new BufferedReader(new
stream, attached InputStreamReader(link.getInputStream(
to socket
)));

Create output PrintWriter out=new


stream, attached PrintWriter(link.getOutputStream(),tru
to socket e);
int numMessages=0;
Read in line
from socket String message=in.readLine();
while(!message.equals("close")) {
System.out.println("Message
recieved.");
numMessages ++; 90
Lab: Server-Socket source code…
Write out line out.println("Message" + numMessages+
to socket ":" + message);
message=in.readLine();
}
}

catch(IOException e)
{
System.out.println("Message is not
recieved");
End of while loop,
loop back and wait for }
another client connection
}
} 91
Client-Socket Programming

• Establishing a stream client involves four


steps:

1- Create a new Socket with a server IP address and


port number.
2- Create input stream and output stream objects.
3- Process stream data and
4- Close the streams.

92
Client-Socket Programming cont’d…

 The client program establishes a connection to the


server program on a particular host and port
number in its listenSocket method, and

 It then sends data entered by the end user to the


server program.

 The listenSocket method also receives the data


back from the server and prints it to the command
line.

93
Client-Socket Programming cont’d…
listenSocket Method
 The listenSocket method first creates a Socket object
with the IP address (“local host”) and port number (1234)
where the server program is listening for client connection
requests.
Socket link= new Socket(host,PORT);

• It then provide a place where the data shall be stored by


creating BufferedReader object to read the streams
sent by the server back to the client.
BufferedReader in=new BufferedReader(
new
InputStreamReader(link.getInputStream()));
94
Client-Socket Programming cont’d…

 Next, it creates a PrintWriter object to send data over


the socket connection to the server program.
PrintWriter out=
new
PrintWriter(link.getOutputStream(),true);

 It also creates a BufferedReader object Set up stream


for keyboard entry...

BufferedReader userentry=new BufferedReader(


new InputStreamReader(System.in));
95
Client-Socket Programming cont’d…
 This listenSocket method code gets the input streams and
passes it to the PrintWriter object, which then sends it over the
socket connection to the server program.

 Lastly, it receives the input text sent back to it by the server and
prints the streams out.
String message, response;
do {
System.out.print("Enter message:");
message=userentry.readLine();
out.println(message);
response=in.readLine();
System.out.println("\nSERVER>" + response);
} while(!message.equals("close"));

96
Lab: Client-Socket Programming
import java.io.*;
import java.net.*;
public class Client {
private static InetAddress host;
private static final int PORT=1234;
public static void main(String[] args) throws
IOException {
Server is try {
local host=InetAddress.getLocalHost();
}
catch(UnknownHostException e)
{
System.out.println("Host id not found!");
System.exit(-1);
}
listenSocket();
}
97
Lab: Client-Socket Programming
public static void listenSocket() {
Socket link=null;
Create try {
client socket, link=new Socket(host,PORT);}
connect to server
catch(IOException e){
System.out.println("Unable to connect");
System.exit(-1);}
Create
try {
input stream
attached to socket BufferedReader in=new BufferedReader(new
InputStreamReader(link.getInputStream()));
Create PrintWriter out=new
output stream PrintWriter(link.getOutputStream(),true);
attached to socket

Create BufferedReader userentry=new


input stream for BufferedReader(new
InputStreamReader(System.in));
user entry

String message, response; 98


Client-Socket Programming …
do {
System.out.print("Enter message:");
message=userentry.readLine();
out.println(message);
response=in.readLine();
System.out.println("\nSERVER>" + response);
} while(!message.equals("close"));
}
catch(IOException e)
{
System.out.println("Message is not sent.");
}
}
}
99

You might also like