A TCP/IP Networking Example: Figure 0.1. A Simple Web Request
A TCP/IP Networking Example: Figure 0.1. A Simple Web Request
Consider a web browser (a web client) at a host with name Argon.cerf.edu (“Argon”) that makes
a web access to a web server on a host with name Neon.cerf.edu (“Neon”).1 The web access is
illustrated in Figure 0.1. Both hosts are connected to the Internet. The web access is a request
for the home page of the web server with URL http://Neon.cerf.edu/index.html.
We will explore what happens in the network when the web request is issued. We proceed, by
following the steps that are performed by network protocols until the first packet from Argon
reaches the web server at Neon. An outline of the steps involved is given in the table below.
The example in this section is based on real traffic measurements, however, the names of the
host have been changed.
A web client and a web server are programs that interact with each other using the Hypertext
Transfer Protocol (HTTP). HTTP is a client-server protocol; the web client runs an HTTP client
program and the web server runs an HTTP server program. When a web client requests a web
page, the HTTP client sends an HTTP Request message to the HTTP server. When the web
server finds the web page, the HTTP server sends the page in an HTTP Reply message.
HTTP uses the Transmission Control Protocol (TCP) to deliver data between the HTTP client
and the HTTP server. When the HTTP client at Argon wants to send an HTTP request, it must
first establish a TCP connection to the HTTP server at Neon (see Figure 0.2).
1
Throughout we use the term host refers to a computer , or more generally, to any end system of communications.
1. Web client at Argon starts an HTTP Request.
2. Argon contacts its DNS server to translate the domain name “neon.cerf.edu” into IP address
“128.143.71.21” and looks up the well-known port number of the web server (port 80).
3. The HTTP client at Argon requests a TCP connection to port 80 at IP address
128.143.71.21.
4. The TCP client at Argon requests its Internet Protocol (IP) to deliver an IP datagram with
the connection request to destination 128.143.71.21.
5. The IP process at Argon decides that it cannot deliver the IP datagram directly, and decides
to send the IP datagram to its default gateway 128.143.137.1.
6. The Address Resolution Protocol (ARP) at Argon sends an ARP request for the MAC
address of IP address 128.143.137.1.
7. The ARP request is broadcast by the E thernet device driver at Argon to all devices on the
Ethernet network.
8. The router with IP address 128.143.137.1 responds with an ARP Response to Argon which
includes MAC address 00:e0:f9:23:a8:20.
9. The IP process at Argon asks its Ethernet device driver to send the IP datagram in an
Ethernet frame to MAC address 00:e0:f9:23:a8:20.
10. Ethernet device driver at router with MAC address 00:e0:f9:23:a8:20 unpacks the IP
datagram, and passes it to its IP process.
11. The IP process at the router decides that it can deliv er the IP datagram with destination
128.143.137.21 directly (without the need of additional routers).
12. The Address Resolution Protocol (ARP) at the router sends an ARP request for the MAC
address of IP address 128.143.137.21.
13. The ARP request is broadcast by the Ethernet device driver at the router to all devices on the
Ethernet network.
14. Neon (which has IP address 128.143.137.21) responds with an ARP Response to the router
which includes MAC address 00:20:af:03:98:28.
15. The IP process at the router asks its Ethernet device driver to send the IP datagram in an
Ethernet frame to MAC address 00:20:af:03:98:28.
16. The Ethernet device driver at Neon unpacks the IP datagram contained in the Ethernet
frame, and passes it to its IP process.
17. The IP process unpacks the TCP connection request contained in the IP datagram and passes
it to the TCP server at port 80.
18. The TCP server at port 80 processes the TCP connection request.
0.2
Argon Neon
Before the HTTP client at Argon can ask the TCP protocol to establish a connection, it must
resolve an addressing issue. The TCP protocol expects that addresses be written in terms of an
IP address and a port number. An IP address is a 32-bit identifier that uniquely identifies a
network interface connected to the Internet. Every network interface that is connected to the
Internet has an IP address. The IP address of Argon’s network interface is 128.143.137.144.
Each byte (1 byte = 8 bits2) of the IP address is written as a decimal number, and the four
numbers are separated by periods. A port number is a 16-bit address that can be used to identify
an application program on a system. Together, an IP address and a port number can uniquely
identify an application on the Internet.
neon.cerf.edu
argon.cerf.edu 128.143.136.15
Figure 0.3. A DNS lookup for the IP address
Le us now see how the HTTP client at Argon determines the IP address and the port number of
the web server at Neon. The IP address is determined using an Internet-wide address translation
service, called the Domain Name System (DNS), that translates symbolic domain names, such as
Neon.cerf.edu, into IP addresses, and vice versa. A host invokes the DNS service by sending a
request to its DNS server. The location of the DNS server of a host is part of the network
configuration of a host. Skipping over a lot of detail, Argon sends a query to its DNS server with
the domain name “Neon.cerf.edu”, and obtains in return the IP address for 128.143.71.21 (see
Figure 0.3).
2
Throughout this book, we use the convention that 1 byte is always 8 bits. The networking literature also uses the term “octet”
to refer to a group of 8 bits.
0.3
Once the IP address is obtained, determining the port number of the HTTP server at Neon is
simple. On the Internet, the server programs of widely used applications have permanently
assigned port number, called well-known port numbers, and are stored in a configuration file of
a host. The well-known port number of an HTTP server is port 80. When Argon contacts the
HTTP server of Neon it assumes that the web server is reachable at port number 80.
Now, the HTTP client at Argon has the information needed to establish a TCP connection, and
requests a TCP connection to port 80 at IP address 128.143.71.21. Like HTTP, TCP is a client-
server protocol. The party that initiates the connection is called the TCP client. The party that is
waiting for connection is called the TCP server. When a web server is started, the HTTP server
sets up a TCP server that is waiting on the well-known port 80 for requests for TCP
connections. The details of establishing a TCP connection a covered later in this book. Here we
only note that the establishment of a TCP connection involves three steps: (1) the TCP client
sends a TCP connection request to the TCP server, (2) the TCP server responds to the request,
(3) the TCP client acknowledges this response and starts to send data. Here, we only follow the
first step of the connection establishment procedure, where TCP sends a connection request to
port 80 of IP address 128.143.71.21. We point out that this connection request does not contain
any data. The HTTP request with the URL will be sent in the third step of the establishment
procedure.
We now follow the steps that are involved to deliver the TCP connection request from Argon to
Neon. The TCP client at Argon asks IP, the Internet Protocol, to deliver the connection request
to IP address 128.143.71.21. IP takes the connection request, encapsulates it in an IP datagram
(an IP datagram is the name of a packet in the Internet protocol), and delivers the IP datagram to
Neon.
The network shown in Figure 0.4 gives an overview of what is involved in delivering the IP
datagram from Argon to Neon. The figure shows that Argon and Neon are each connected to an
Ethernet local area network. The picture shows that the path (route), of an IP datagram from
Argon to Neon goes through a router which connects the two Ethernet. A router, also called IP
router or gateway, is a switching device with multiple network interface cards (NICs), which
takes an IP datagram that arrives on one of its network interfaces and forwards the datagram on
a different interface, with the intent to move the IP datagram closer to its destination. The
forwarding decision is based on a routing table, which lists the name of a network interface for a
set of destination addresses. Note in Figure 0.4 that the router has a domain name and an IP
address for each of its network interfaces.
When Argon has the IP datagram for destination 128.143.71.21, it does not know the route that
the IP datagram will take to its destination. The IP module at Argon merely determines if the IP
datagram can be delivered directly to Neon, or if the datagram must be send to a router. A
datagram can be delivered directly without the need for intermediate routers, if the sender and
receiver are both connected to the same local network. Argon makes a decision whether Neon is
on the same local network, by comparing the IP address of Neon with its own IP address. In
this particular case, Argon assumes that IP addresses that match its own IP address
0.4
(128.143.137.144) in the first three bytes belong to interfaces that are on the same local network
as Argon, and all other IP addresses are not on the same local network. With this criterion, Neon
is on a different local network and Argon tries to forward the IP datagram to its default gateway.
The default gateway of a host is the IP address of a router, and is part of the network
configuration of any host. Argon’s default gateway is 128.143.137.1, with domain name
router137.cerf.edu (“Router137”). Therefore, Argon sends the IP datagram to Router137.
Figure 0.4. The route between Argon and Neon. The router in the center of the figure is referred to by any of the names
associated its interfaces (“Router137” or “Router71”).
To forward the IP datagram to the default gateway 128.143.137.1, Argon passes the IP
datagram to the Ethernet device driver of its network interface card. The device driver will
insert the IP datagram in an Ethernet frame (Ethernet packets are called frames), and transmit
the frame on the Ethernet network. However, Ethernet frames do not use IP addresses, but have
an addressing scheme that is based on 48 bit long MAC (media access control) addresses. MAC
addresses are written in hexadecimal notation, where each byte is separated by a colon or a
hyphen. For example, Argon’s MAC address is 00:a0:24:71:e4:44. Each Ethernet frame
contains the MAC addresses of the source and the destination of the frame. Before IP can pass
the datagram to the Ethernet device driver, it must find out the MAC address that corresponds to
IP address 128.143.137.1. The translation between IP addresses and MAC addresses is done
with the help of the Address Resolution Protocol (ARP).
The translation of addresses using ARP and the subsequent transmission of the frame that holds
the IP datagram steps are shown in Figure 0.5. First, Argon sends out an ARP message of the
0.5
form “What is the MAC address of 128.143.137.1?”. The ARP message is sent in an Ethernet
frame that is broadcast to all Ethernet devices on the same network. When Router137, which
has IP address 128.143.137.1, receives the ARP message, it responds with an ARP message that
states “IP address 128.143.137.1 belongs to MAC address 00:e0:f9:23:a8:20”. Finally, when
Argon receives this message, it passes the MAC address of the default gateway together with the
IP datagram to the device driver and transmits the frame. In total, three Ethernet frames are
transmitted on the Ethernet network. (We note that subsequent transmissions of IP datagrams
from Argon to Router137 do not require ARP messages. Argon keeps a list of known MAC
addresses in a local table.)
When Router137 receives the Ethernet frame from Argon, it first extracts the IP datagram and
passes the datagram to the IP module. Once Router137 receives the IP datagram from Argon, it
makes a similar decision as Argon, that is, it determines if the datagram can be forwarded
directly to Neon or it selects a router from its local routing table and forwards the packet to
another router. Router137 has multiple network interfaces, and, therefore, checks if the
destination of the IP datagram is directly through any of its interfaces. To determine if a node is
locally reachable, the router tries to match the first three bytes of the IP address of Neon, which
is included in the IP datagram, to the IP addresses of its own interfaces: 128.143.137.1 and
128.143.71.1. Since a match occurs for 128.143.71.1, the router tries to forward the IP datagram
directly to Neon.
The transmission of the IP datagram from the router to Neon, goes through the same steps as the
delivery of the IP datagram from Argon to the router. First, the router acquires the Ethernet
address of Neon, by sending an ARP request on the Ethernet interface which is associated with
IP address 128.143.71.21. Neon sends its MAC address, 00:20:af:03:98:28, in an ARP response
message. As soon as the router receives the MAC address of Neon, it sends an Ethernet frame
that contains the IP datagram to Neon. Again, three Ethernet frames are as shown in Figure 0.6.
0.6
Figure 0.6. Ethernet frames transmitted to deliver the IP datagram from the router to Neon.
When Neon receives the Ethernet frame from Router713, it first extracts the IP datagram, and
then delivers the TCP segment to the TCP server at port 80. At this time, the delivery of the first
IP datagram from Argon to Neon, which contains the TCP connection request, is completed.
What will happen next is that the TCP server at Neon responds to the TCP connection request,
which involves the transmission of an IP datagram from Neon to Argon. The steps involved in
delivering this IP datagram are identical to what we saw earlier. When the response is received
at Argon, Argon can start to transmit the HTTP request.
The above description gives a good picture of the complexity of transferring data from one host
to another. As you work your way through the chapters of this book, you will become familiar
with each of the steps described above and you will understand the intricacies of this example.
3
Note that from the perspective of Neon, the domain name of the router is router71.cerf.edu.
0.7
2. The TCP/IP protocol suite
The transport of data as shown in the example in the previous section is governed by a set of
protocols that constitutes the TCP/IP protocol suite, also called Internet protocol architecture or
Internet protocol stack. The protocols are organized in four layers, as shown in Figure 0.8: an
application layer, a transport layer, a network layer, and a data link (or network interface) layer.
Each protocol is assigned to one layer. At any given layer, a protocol requests the services of a
protocol in a layer immediately below it, and provides services to a protocol in a layer
immediately above it. The service requests generally relate to the delivery of data. This is
shown in Figure 0.7, for the Web example from the previous section. When the HTTP client at
Argon wants to send an HTTP request to the HTTP server at Neon, it requests from TCP the
establishment of a TCP connection. Then TCP requests from IP the transmission of an IP
datagram, which, in turn, requests from the Ethernet device driver the delivery of an Ethernet
frame. Not shown in the figure is that the Ethernet device driver requests transmission from the
MAC layer, which, in turn, requests the transmission of a bit stream. Whenever a protocol at a
certain protocol layer wants to send data to a remote peer at the same layer, it actually passes the
data to the layer below it, and asks that layer to perform the delivery of data. In this way, data
can be thought of as traveling vertically through the protocol stack.
argon.cerf.edu
HTTP client
TCP client
Send an IP datagram to
128.143.71.21
IP module
Ethernet
0.8
2.1. An Overview of the TCP/IP protocol suite
The TCP/IP protocol suite does not specify nor require specific networking hardware. The only
assumption that the TCP/IP protocol suite makes is that the networking hardware, also called
physical network, supports the transmission of an IP datagram. The lowest layer of the TCP/IP
protocol suite, the data link layer, is concerned with interfacing to a physical network.
Whenever a new network hardware technology emerges all that is needed to run Internet
applications over the new hardware is an interface at the data link layer that supports the
transmission of an IP datagram packet over the new hardware. This minimal dependence of the
TCP/IP protocol suite on the underlying networking hardware contributes significantly to the
ability of the Internet protocols to adapt to advances in networking hardware.
Transport
Operating system
Network
Data Link
We next provide an overview of the layers of the TCP/IP protocol suite. At the application layer
are protocols that support application programs. For example, the HTTP protocol is an
application layer protocol that supports web browsers and web servers. Other protocols at the
application layer are support of electronic mail (POP3, SMTP), file transfers (FTP), or
command line interfaces to remote computers (Telnet, SSH).
The transport layer, also called host-to-host layer, is responsible for the exchange of
application-layer messages between hosts. There are two transport-layer protocols in the TCP/IP
protocol suite: the Transport Control Protocol (TCP) and the User Datagram Protocol (UDP).
TCP offers a reliable data service which ensures that all data from the sender is received at the
destination. If data is lost or corrupted in the network, TCP will perform a retransmission. UDP
is a much simpler protocol which does not make guarantees that delivery of data is successful.
The network layer, also called internet layer, addresses issues involved with forwarding data
from a host to the destination across intermediate routers. All data transport at the network layer
is handled by the Internet Protocol (IP). IP receives support from other protocols, such as the
Internet Control and Messaging Protocol (ICMP) and the Internet Group Management Protocol
0.9
(IGMP) which perform error reporting and other functions. Also, IP relies on routing protocols,
such as the Routing Information Protocol (RIP) or Open Shortest Path First (OSFP), or Border
Gateway Protocol (BGP), which determine the content of the routing table at IP routers.
The data link layer, also called network access layer or interface layer, is concerned with
sending and receiving data across either a point-to-point link or a local area network. There is a
large variety data link layer protocols for local area networks and point to point links. Each data
link layer protocol offers a hardware independent interface to the networking hardware. The
functions of a data link layer protocol are partially implemented in hardware (on the network
interface card) and partially in software (in the device driver). Most local area networks are
broadcast networks where the transmission of a packet can be received by more than one host.
In such networks, the data link layer has a sub-layer, which is called the Media Access Control
(MAC) layer. The MAC layer can be thought of as residing at the bottom of the data link layer.
The MAC layer runs a protocol that determines when a station on the local area network has
permission to transmit. The MAC layer is realized in hardware on the network interface card
and is not visible at the network layer or higher layers. Below the data link layer is the physical
layer, which consists of the hardware that generates and interprets electrical or optical signals,
and the cables and connectors that carry the signals.
IP IP protocol IP IP protocol IP
Figure 0.9 shows the protocols that are involved in the web access example between Argon and
Neon. At each host, the figure shows protocol instantiations (entities) for HTTP, TCP, IP and
Ethernet, where the Ethernet entity encompasses the data link layer, including the MAC layer,
and the physical layer. At each layer, a protocol entity interacts with an entity of the same layer
at a different system. The HTTP client at Argon interacts with an HTTP server at Neon, the TCP
client at Argon interacts with the TCP server at Neon, and the IP and Ethernet entities at the
hosts interact with corresponding entities at the router. Figure 0.9 illustrates that the routers do
not have entities at the transport and application layer. Protocols at these layers are end-to-end
0.10
protocols, and are not aware of the existence or the number of routers between two hosts.
Conversely, routers do not interpret messages at the application or transport layer.
In Figure 0.10 we show the assignment of all protocols discussed in this book to the layers of
the TCP/IP protocol suite. Figure 0.10 is not complete and shows only a subset of the protocols
used in the TCP/IP protocol suite. An arrow in the figure indicates how protocols request
services from each other. For example, HTTP requests the services of TCP, which, in turn,
requests the services of IP, and so on. Figure 0.10 shows protocols that we have not mentioned
so far. SNMP, the Simple Network Management Protocol, is used for remote monitoring and
administration of equipment in an IP network. With exception of the ping program, all
applications shown in the figure use the services of TCP or UDP, or, as in the case of DNS,
both.
RIP, OSPF and PIM are routing protocols which determine the content of the routing tables at
IP routers. Interestingly, RIP sends routing messages with UDP, a transport layer protocol.
ICMP is a helper protocol to IP, which performs error reporting and other functions. IGMP is
used for group communications.
The ARP protocol, which translates IP addresses to MAC addresses, so that IP can send frames
over a local area network communicates directly with the data link layer.
Figure 0.10 clearly illustrates the central role of IP in the TCP/IP protocol suite. IP carries all
application data, and can neither be bypassed nor replaced.
0.11
ping Application
application HTTP Telnet FTP DNS SNMP
Layer
Routing Protocols
ICMP RIP
Network
IGMP IP PIM
Layer
OSPF
DHCP
Network
Interface
When data is passed from a higher layer to the next lower layer, a certain amount of control
information is attached to the data. The control information is generally added in front of the
data, and is called a header. If the control information is appended to the data, it is called a
trailer. All protocols have headers and, but only very few have trailers. The process of adding
header and trailers to data is called encapsulation. The data between the header and the trailer is
called the payload. Together, header, payload, and (if present) trailer, make up a protocol data
unit. There is a convention for naming protocol data units in the TCP/IP protocol suite: In TCP
they are called segments, in UDP and IP, they are called datagrams, and at the data link layer,
they are called frames. The generic name packet is used when the protocol data unit does not
refer to a specific protocol or layer. The encapsulation process is illustrated in Figure 0.11. The
protocol data unit at one layer makes up the payload at the next lower layer. Each layer adds a
header and, in addition, Ethernet also adds a trailer. In this way, the overhead for sending
application layer data increases with each layer.
0.12
Headers (and trailers) from a given layer are processed only by entities at the same layer. The
header of a transmitted TCP segment is processed only by the TCP protocol at the host which
receives the TCP segment. Each header of a protocol data unit is formatted into a number of
protocol specific fields. The format of the header is part of the specification of a protocol.
Header fields contain, among others, a source and a destination address, a checksum for error
control, sequence numbers, and the length of the payload. If the header has not a fixed size, then
the size of the header must be included as a field in the header.
At the receiver side, each layer strips off header fields from that layer and passes the payload to
a protocol at the next higher layer. Each layer must decide to which higher-layer protocol to
send the payload to. For example, an Ethernet device driver must assign the payload of a frame
to IP or to ARP. Likewise, IP must assign the payload of an IP datagram to UDP or TCP or
another protocol. This process of assigning the payload to a higher layer protocol is called
demultiplexing. Demultiplexing is done using a field in the header of a protocol data unit, which
identifies a higher layer protocol or an application process. Each protocol has such a
demultiplexing field.
User data
HTTP
HTTP Header User data
TCP
TCP Header HTTP Header User data
IP TCP segment
Ethernet IP datagram
Ethernet Ethernet
IP Header TCP Header HTTP Header User data
Header Trailer
Ethernet frame
0.13
Socket Programming 2
Socket
Socketprogramming
programmingrefers
refersto
toprogramming
programming at
at the
theapplication
applicationleve l/layer!
level/layer!
TCP vs. UDP in • TCP is useful when indefinite amount of data need
Socket Programming to be transferred ‘in order’ and reliably
(cont.) ▪ otherwise, we end up with jumbled files or invalid
information
▪ examples: HTTP, ftp, telnet, …
In
In socket
socket programming
programmingwe wepick
picktransport-layer protocol
transport-layer protocolthat
that has
hasservices
services
that
that best
best match
matchthe
theneeds
needsof
of our
ourapplication.
application.
Client-Server Model 6
• CLIENT:
CLIENT process that initiates communication, requests
service, and receives response
▪ although request-response part can be repeated several
times, whole process is finite and eventually comes to
an end
• SERVER:
SERVER process that passively waits to be contacted
and subsequently provides service to clients
▪ runs infinitely
▪ can be iterative or concurrent
Initiation of
communication
7
Client-Server Model (cont.)
Example [ iterative vs. concurrent servers ]
• CLIENT:
CLIENT • SERVER:
SERVER
(1) create socket Client (1) create socket
(2) repeat: (2) repeat:
Server
(2.a) send Client (running) (2.a) receive
(2.b) receive (2.b) process
(2.c) process (2.c) send
(3) destroy Client
• CLIENT:
CLIENT • SERVER:
SERVER
Client
(1) create socket (1) create socket
(1) Server
(2) listen
Client (running)
Client
Client
(3) repeat
(2) connect (3.a) create new socket
(3) repeat: (3.b) repeat:
Server
(3.a) write Client
(running) (3.b.1) read
(3.b) read (3.b.2) process
(2)
(3.b.3) write
(4) destroy Client (3.c) destroy socket
11
Client-Server Model (cont.)
Java code
to establish ServerSocket servsock = new ServerSocket(port, backlog, bindAddr);
a socket
14
Java Socket Programming (cont.)
java.net package
hello HELLO
Use the following simple client/server
application to demonstrate socket
programming for both TCP and UDP:
1) A client reads a line from its standard
input (keyboard) and sends line out
through its socket to the server.
Server: HELLO
Java Socket Programming with UDP 16
Server
Client (running)
write reply to
HELLO serverSocket
specifying client’s
read reply from host address &
clientSocket port number
close
clientSocket
17
Java Socket Programming with UDP (cont.)
import java.io.*;
import java.net.*;
class UDPClient {
clientSocket.send(sendPacket);
send
senddatagram
datagram
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
while
whilewaiting
waitingfor
for
response,
response,create
create
placeholder
placeholderfor
forpacket
packet clientSocket.receive(receivePacket);
read
String modifiedSentence = new String(receivePacket.getData());
readdatagram
datagram
extract
System.out.println(“FROM SERVER: “+modifiedSentence.trim());
extractdata
datafrom
from
receivePacket
receivePacketbuffer
buffer
and
andperform
performtype
type clientSocket.close();
conversion
conversion
}
}
19
Java Socket Programming with UDP (cont.)
server on blue.cs.yorku.ca …
import java.io.*;
import java.net.*;
class UDPServer {
while(true) {
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
20
Java Socket Programming with UDP (cont.)
get
getport
portnumber
number
int port = receivePacket.getPort();
of
of thesender
the sender
String capitalizedSentence = sentence.toUpperCase() + ‘\n’;
sendData = capitalizedSentence.getBytes();
create
createdatagram
datagram
to
to sendto
send toclient
client DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, port);
write
writedatagram
datagram
to
tosocket
socket
serverSocket.send(sendPacket);
loop
}
loopback
backand
and
wait
wait foranother
for another }
datagram
datagram }
Java Socket Programming with TCP 21
Server
Client (running)
TCP
connection wait for
create socket, setup incoming requests
connect to server
clientSocket = new Socket()
create new socket
connectionSocket = welcomeSocket.accept()
close
close connectionSocket
clientSocket
22
Java Socket Programming with TCP (cont.)
inFromServer
import java.io.*;
import java.net.*; TCP
socket
outToServer
class TCPClient {
String sentence;
String modifiedSentence;
create
createinput
inputstream
stream
attached
attachedtotokeyboard
keyboard BufferedReader inFromUser = new BufferedReader (new
InputStreamReader(System.in));
create
createsocket;
socket;
connect
connect it toserver
it to server Socket clientSocket = new Socket(“blue.cs.yorku.ca”, 5555);
server runs on blue
- port 5555
DataOutputStream outToServer =
create
createoutput
outputstream
stream new DataOutputStream (clientSocket.getOutputStream());
attached
attachedto
tosocket
socket
BufferedReader inFromServer = new BufferedReader (new
create
createinput
inputstream
stream
InputStreamReader(clientSocket.getInputStream()));
attached to socket
attached to socket
23
Java Socket Programming with TCP (cont.)
place
placeline
linetyped
typedbyby
user into ‘sentence’;
user into ‘sentence’;
‘sentence’
‘sentence’continues
continuesto
to
gather characters
gather characters sentence = inFromUser.readLine();
until
untilaacarriage
carriagereturn
return
outToServer.writeBytes(sentence + ‘\n’);
send
sendline
lineto
toserver
server
modifiedSentence = inFromServer.readLine();
print
printto
tomonitor
monitor
line
line read fromserver
read from server System.out.println(“FROM SERVER: “+modifiedSentence);
clientSocket.close();
}
}
24
Java Socket Programming with TCP (cont.)
server on blue.cs.yorku.ca … inFromServer
TCP
import java.io.*; socket
import java.net.*;
outToServer
class TCPServer {
String clientSentence;
String capitalizedSentence;
create
createwelcoming
welcoming
socket
socketat
atport
port5555
5555 ServerSocket welcomeSocket = new ServerSocket(5555);
wait
waitfor
forcontact-
contact- while(true) {
request
requestby
byclients
clients
create
create&&attach
attachoutput
output DataOutputStream outToClient =
stream to new socket
stream to new socket
new DataOutputStream(connectionSocket.getOutputStream());
read
readfrom
fromsocket
socket clientSentence = inFromClient.readLine();
write
writeto
tosocket
socket capitalizedSentence = clientSentence.toUpperCase() + ‘\n’;
outToClient.writeBytes(capitalizedSentence);
}
}
}
end
endof
ofwhile
whileloop
loop––wait
wait
for
for anotherclient
another clientto
to
connect
connect
NOTE:
NOTE: This
Thisversion
versionofofTCP
TCPServer
Serveris
isNOT
NOTactually
actuallyserve
serveclients
clientsconcurrently,
concurrently,
but
butititcan
canbe
beeasily
easilymodified
modified(with
(withthreads)
threads)to
todo
doso.
so.
Java Socket Programming – Multicast 26
A user subscribes to the service by ‘tuning in’ to the right multicast IP address.
Source: http://www.cswl.com/whiteppr/tutorials/modified.html
27
Java Socket Programming – Multicast (cont.)
import java.io.*;
import java.util.*;
class MulticastServer {
MulticastSocket socket;
DatagramPacket packet;
create
createmulticast
multicastsocket
socket InetAddress address = InetAddress.getByName("224.1.1.1");
–– socket
socketisisbound
boundtoto
any available local port
any available local port
socket = new MulticastSocket();
datagram
datagramdestined
destinedto to
while(true){
all
all clients listeningto
clients listening to Thread.sleep(5000);
destPort
destPortwhowhoare
are
members of 224.1.1.1 System.out.println("Sending ");
members of 224.1.1.1
multicast
multicastgroup
group String str = (new Date()).toString();
data = str.getBytes();
packet = new DatagramPacket
send
senddatagram
datagram (data, str.length(), address, destPORT);
socket.send(packet);
}
}
}
29
Java Socket Programming – Multicast (cont.)
import java.net.*;
import java.io.*;
class MulticastClient {
while(true){
print
printsender’s
sender’sunicast
unicast socket.receive(packet);
IP
IP addressand
address and
received message
received message
String str = new String(packet.getData());
System.out.println(" Time signal received from"+
packet.getAddress() + " Time is : " +str);
extract
extractsender’s
IP
sender’s }
IPaddress
address
}
}
Exercise 31
1. Check for yourself whether the server in “multicast time/date server” could
use a simple DatagramSocket instead of MulticastSocket?
Would the application performance change?
Justify your observation!