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

Networkin

..:.,. Q 8.J.
V Advanced Java Programming (MSBTE)
4•2- ~
4 .2.1 Client--Server .
. I' nt/server. According to computer 11
.
Th k d ppllcatJon is c ,e · etw0 L
e most common term that you hear in any networ e a · . that simply wants to gain access to P . r,
• • II · t is anything art1c~ 1•1
a server ts anything that has some resources to share and a c en °
resource(s) of server
• The network client makes request
1 th
The cli ent and server communicates over the network through protoco s. each request and returning res I to '
'-erv b d' . h 1· ts by working on n be connected together ·
u ts baI
- er Y sen mg messages and the server responds to t elr c ,en c.
to th em . Generally~one server handles numerous clients and finally multiple servers ca tn a gro~p
to han dle the increased processing load because of increased number of cli ents.
. . rver socket that allows a single comput
Accordmg to Berkeley socket there are two types of sockets. One is se· client socket t h at connects to servers er to
. ' d 0
serve different types of information to different clients at once and secon ,s tket
and requests.
The Berkeley socket has also introduced another term, called as port. The port is specia l type of numbered socket to
th
whi ch client connects. A server is allowed to accept multiple clients' conne ctions; conne ct ed to e same port number,
although each session is un iquely maintained by TCP/ UDP connecti on. To manage multiple client connections, a server
process must be multithreaded or have some sort of real-time system to work on input out put.

4.2.2 Reserved Sockets


In Section 4 .2, we have discussed about sockets antl ports. We cam e t o know t hat, po rt is special type of numbered
socket to which client connects. Once a client connects t o a server port, the higher level prot ocol ensures on which
protocol we are connected. TCP/IP has reserved some socket ports for precised protocols, ca lled as reserved sockets,
The re are around 1024 reserved ports. Th e Table 4.2. 1 sh ows some we ll-known reserved sockets with port numbers.

Table 4.2.1

Sr. No. Port Number Protocols

1. 20 and 21 File Transfer Protocol (FTP}


2. 22 Secure Shell, SSH
3. 23 Telnet
4. 25 Simple Mail Transfer Protocol, SMTP
5. 53 Domain Name System, DNS
6. 69 Trivial File Transfer Protocol, TFTP
7. 79 finger
8. 80 Hypertext Transfer Protocol, HTTP
9. 110 Post Office Protocol v3, POP3
10. 119 Network News Protocol, NNTP
11. 161 an d 162 Simple Net work Man
agement Protocol, SNMP
12. 443 Secure Sockets layer ov H
e~ TTP, HTTP$
4.2.3 Proxy Servers
.
There is a common situation that in most institutes' computer lab oratories . •on
t he I' . stnctr
on accessing particular website(s). In ot her words, some website(s) a bl c ients/students has certain re i·enl
re ocked f 1· a c'
would connect to a proxy server, an d proxy server will commun icat . or c 1ents/students. In this case , the
. e with serv f er ,s
virtual server that speaks the client side of a protocol to another server Al er or the client. The proxy sefl/ . . ~al
abilities, such as : · ong Wi t h th is, a proxy server has manY additiO

________ ~
_:· -
1liY' p110 1lt
\r
• Advanced Java Programming (MSBTE)
4-3 Networking Basics
;;;#
(·,) Filter certain requests or cache the result
so
f th
ose requests for future use.
(ii) set upload and download limit.

(·,·,,·) Fetch the contents of a web server's p opu 1ar pages once and save it to provide faster access to c1·ren ts ·
th
(iv) Shows e graphical analysis (a graph) of uploaded and downloaded data packets.

4.2.4 Internet Addressing

An internet addres~ is a number that uniquely identifies each computer on the internet. There are two internet
addressing schemes available currently. One is consisting 32-bit values, called 1Pv4 and second consisting 12B-bit values,
called IPv6.

Obviously the 1Pv6 is advantageous than IPv4. One say, IPvS supports larger address space than IPv4. In current
internet world 1Pv4 is most widely used scheme but IPv6 will grab the market very soon . .

Because of rising use of 1Pv6, Java has also provided support for that in JDK 1.4. In cu rrent situation, we can say t hat
almost all the environments are supporting IPv6. In many of following examples, we have used IPv4.

The IPv4 is a 32~bit addressing system and is a sequence of fou r numbers/bytes between O to 255 and separated by
dots(.). This numbering makes it easier to remember. There are fhie network classes lettere-d A, B, C, D and E. Acco rding to
the internet addressing standards, first byte specifies t he network d ass and the last byte actually ident ifies t he individual
computer on the network. Followi ng are the basic charact eristics of t hese network classes.

Characteristics of class A networks


(i) Network addresses ranges from 0.0.0.0 t o 127. 255.255.255.

(ii) The leftmost bit is always 0.

(iii) Th e first 8 bits (first byte) defines the netid and the rema ining 24 bits (3 bytes) defines the ho_s tid.

Characteristics of class B networks


(i) Network addresses ranges from 128.0.0.0 to 191.255. 255.255.

(ii) The netid is determined by the fi rst 16 bits (first 2 bytes) and hostid is determined by the last 16 bits (last 2 bytes).

(iii) Th ere are 65,536 possible IP addresses for a single class B network.

(iv) The netid 172. 16.0.0 t o 173.31.0.0 are reserved for special use.

Characteristics of class C networks


(i) Network addresses ranges fro m 192 .0.0.0 to 2 23 -255 -255 ·25 5-

(il) The fi rst 24 bits defines the netid an d remaining 8 bits defines the hostid.

are 2,097,152 possible IP ad resses f 0 r a single class C net works.


(i'1I) There · d

Characteristics of cf ass D networks


Ii) Network addresses ranges from 224.0.0.0 t o 239.255.255.255.
· or host,·d.
(ii) Ther e ·1s no net,d
(iii) Sp . . .
ec,ally used for multrcastrng.

Characteristics of class E networks


(i) N o to 255.255 .255.255
etwork addresses ranges from 2 39 .o. 0 ·
(Ii) sPec,alfy
. reserved for special use on the Internet.
llii) Th .
~no netid or hostid.
• Techllnowledge
PU b Ii Cat I o n s
• · Ne tworklnq b·
" Adv ance d Java Programmin g (MSBTE 4-4 • q ·, 1,.-.
) d Interfaces - -----
4.3 Jav a and the net : The Networ k"n
I g Classes an
Java prov ides sup port for Pre
Afte r disc ussi ng fund ame ntal conc epts twor , w disc uss hoW
abo ut ne king , let s no Paring
netw orke d appl icat ions .
rf es that are used for crea ting
The java .net pack age prov ides a . f networked
hug e library O classes dand inte
inte ac
rfac es.
appl icat ions . The Tab le 4.3. 1 and Tabl
e 4.3.2 show s th is classes an

Table 4.3.1
I
-
Classes
Aut hent icat or lnetS ocke tAdd ress Sock etlrn pl

Con tent Han dler JarURLC onnectio n Soc ketP erm issio n

Data gram Pack et MulticastSoc ket URI


Data gram Soc ket NetPermission URL
Data gram Soc ketl mpl · NetworkInte rfac e URLClas_sLoa de r
HttpURLCon nect i on Passwor dAu then ticat ion uRLConnect ion
lnet Add ress ServerSocket URLDeco der
lnet 4Ad dres s Socket URLEnco de r
lnet 6Ad dres s SqcketAddress U'RLStre a mH and ler
I

Table 4.3. 2

Interfaces '

Con tent Han dler Fact ory Socketlmpl Fact ory


URL Stre amH andl erFa ctor y
FileNameMap SocketOptions
Dat agra mSo cket lmp lFac to ry
It is not poss ible to cove r all thes e clas
ses and inte rfac es at this stag e. But
inte rfac es are disc usse d in following som e of the mos t imp o rtan t classes
sections. and

4.4 Class lnetAddress

The lnet Add ress class deal s with inte


rnet addr ess by enca psul atin g IP add
class stor es inte rnet add ress es by r_efe ress and the dom ain nam e . An obje
renc'.ng a_ dom ain nam e or IP add ress ct of this
task ove r the inte rnet ; such as making (using its met hod s). We kno w that
a vo1ce/v1deo call, send ing mail onli ne to do an1
ove r the inte rnet , the .inte rnet addr esse pu r h . . h h
s are fund ame ntal . ' c ase or con nect ing wit ot er machines
·
This class prov ides a facility to inte ract
with ot her mac hine s even by u .
The use of host nam e .1s far mor e conv . h
enient and und erst anda bl e then usin sing t e hos t nam e inst ddress,
' ead of using IP a
As disc usse d earl ier ther e are two poss g
ible type s of inte rnet add re . com plex IP add ress es.
both (1Pv6 is supp orte d from JDK 1.4 po~I
onw ards). ss1ng, ·1Pv4 and IP v 6, f ortu
nate Iy th·1s class suP
This library class has a few factory
met hod s (sta tic met hod s) d
Following sect ion will explain a few of · th dsl•
th em . a n a few ·1ns t anc
e met hod s (non -sta tic · me 0
Rem emb er that , the lnetAddress class
has no visib le eonstruct Th
·to use o ne of its insta nce met hod s. hav
The obje cts crea ted by usin g or. e refo re t 0
whi ch retu rn requ ired enti ties . . . c Iass we 1
crea te an inst anc e of t his
st hod>
in ance met hod s are used to invo
ke fact ory 111 et
rif_ .Advanced Java Programming (MSBTE) 4-5 Networking Basics
~
4,4,
factory Methods
·
,he factory met hod s are actually stat' · stance of
· ess wh· htc meth ods def tne
d ·
tn lnetAddress class . These methods return an ,n
rnet addr .
I et
Ad dress class, as inte ' ic is used to . t .
ins ant1ate lnetAddress objects.
n • . df .
Following hst shows the com mon ly us e actory methods :

ocafHost() th ·.
1, static lnetAddress getl rows UnknownHostException
h
2 static lnetAddress getByName(Strin g ost_name) throws UnknownHostException
·
Exception
ring host_name) throws UnknownHost
3. static lnetAddress getA//ByName(St
ption
IP_address) throws UnknownHostExce
4. static lnetAddress getByAddress(String
getByName( ) method returns an
st th internet address of the local host. The
The getLocalHo ( ) me od returns the
y of inter net addresses th at
th e ho5t_na me passed to it. The getA!IByName( ) method returns an arra
internet address of
returns th e inte rnet
addresses that a particular host_nam
e resolves to. The getByAddress( ) method
represent all of the
address concerned with the specified IP_
address.

invokes th!s factory meth ods must


nHo stException therefore· ttie method that
Note : All these methods throws Unknow
catch or throw UnknownHostException.

ose of factory methods.


Program 4.4.1 : Write a program to display the purp

import java.net. '~;

class FactoryMethodsDemo

ception
. (Stri' ncro a:r[ ]) thro~s UnknownHostEx
pu bli c stati.c vo1 mam
'd

InetAdd ress add rl = InetAddress.getLocalHost( );


System. out.println (add r1);
· tByN ame("msbte.o:rg.in ");
. ·
InetAdd ress .a ddr2 = InetAddress.ge
System.out.prin tln (add r2 ); I . ")
- I tAddress.getAllByName( www.goog e. com ;
II

InetAddress add r3 [ 1- ne
t
for (int i = O; i <ad dr3. leng b; i + +)

System.out.printl n(ad dr3 [i]);

V
Y
Tn lrllnoll!lellwii
P u bllcat 1o n s
4-6
,., Advanced Java Programming (MSBTE)

Output:

· va
C: \jdkl.8\bi n> j avac FactoryMethodsDem o.Ja

C: \jdkl . 8\bin>j ava FactoryMethodsDemo


DESKTOP-RB6D08M/192 .168.43.20 6
msbte. org.in/43 . 240.64.24 1
-MW .google.co m/216 . 58 . 203 . 132

C: \jdkl .8\bin >

4.4.2 Instance Methods


th t returns different entities based on invoking
The instan ce methods are non-static methods of lnetAddress class a
object.
Following are the commonly used instance methods:

1. boolean equa/s(Object another_obj)

2. byte[] getAddres s()

3. String getHostAddress()

4. String getHostN ame()

boolean isMulticastAddress()

-r::.. ~
5.

6. String toString() . ·

• ~ ~ ~ The equals(} returns boolean true it invoking object has t he same Internet address as
another_o bj otherw ise returns
The
l- !..~ boolean false . The getAddress() returns a byte array that represents t he invoking object's Internet address in network.
·v getHostAddress( ) returns a string that represents the host address associated w ith the invoking
lnetAddre ss object. The
lnetAddre ss object.
getHostN ame( ) returns a string that represents the host name associat ed with the invoking
otherwise f alse. The
The isMulticastAddress( ) returns true if invoking Int ernet address is a multicast address,
t oSt ring( ) returns the encapsula ted string containing the host name and IP address.

Program 4.4.2 : Write a program that demonstrates the use of instance methods of lnetAddre ss class.

import java.n et. *;


class InstanceM ethodsDem o
{
public static void main(S Lring ar[]) Lhrows Exception
{
InetAdd.ress addrl = InetAddre ss.getByName("ptu.ac.in") ;
lnetAddre ss addr2 = InetAddre ss.getByN ame("msbte.org.in'i);
System.ou t.println( \nls " + addrl + . equ als + addr2 + ?· ·. " + a ddr·I .equals(a ddr2)) ;
11 11
11 11

+ addrl + is:" + add r 1 .getH osLAddres


11
11
System.ou t.println( \nHost·Ad dress of
11
.
· · s ( )) ·
System.ou t.println( \nHost Name of +
11
11
addrl + is:'' + 11
addrl tH N '
~e~(~)~)1;=== ==:a~
tf=== ==== ==== ==~~~ ~==== =====.======~~~-Jg~e~g;os~t~am V ~
~~ puo titl'•
r, dvanced Java Programming {MSBTE)
- Networking Basics
.
it, L . 4-7
. .
;e:::::. System.out.println("\nls + addr 1 + 11 a .
11

S tern.out. · ti ·(''\ C . Multicast Address? : " + addrl.i sMulti castAd dress( )),
ys pnn n n on version of" +
addrl + "to string is : " + addrl.t:oString( ));
}

output:

.
C:\jdkl .8\bin> javac InstanceMethod s Demo.Java
:\jdkl. 8\bin> java InstanceMethodsDemo
.
I s ptu.ac. in/117 .239.1 78.135 equals ms bt e.org.i n/43.24 false
0.64.24 1

ost Address of ptu.ac. in/117 .239.17 8.135 is : 117.239 .178.13 5


·
ost Name •Of ptu. ac. in/117 . 239 .178 .135 is .. pt u.ac.rn

I s ptu.ac. in/117 .239.1 78.135 a Multic ast Address? : false

in/117. 239.17 8.135


Conversi on of ptu.ac. in/117 .239.17 8.135 to string is: ptu.ac.

C: \jdk1. 8\bio> .

4.5 TCP/IP Client Socket


networked programs that executes across multipl e
As discus$ed in earlier TCP/IP sockets are used in writing
n of classes and interfaces that provides low level
computers over the networ k. The java.net package provides collectio
communication suppor t betwee n comput ers.

The most widely used classes for socket programming are :

(i) java.net.Socket

(ii) java.net.ServerSocket
cl ass java.net.ServerSocket is discuss ed in next section .
(i) In this section we will discuss on class java.net.Socket; wh ereas,
client and server use t o commu nicate with each other
(ii) The class java.net.Socket represe nts the socket that both the
as:
(Generally, preferre d for definin g client object s). This cl ass is defined

Public dass Socket extend s Object implements Closeable


class.
The following list shows the overl oaded constru ctors of Socket

l. Socket( J
2
· Socket(lnetAddress address, int port)
3. Socket(lnetAddress address, int port, tnetAddress /oca/Addr, int
/oca/Port}

4
· Socket(Proxy proxy}

s. 50cket(Socketlmpl imp/}
6
' 50cket(String host, int port}
7. /oca/Ad dr, int /ocafPort)
- - - - - - - - - - - --::.. :=::-~ --
5
'------.. . . ___~ ( Str;ing host, int·~p~o~rt~,~/n~e~tA::d:d~re=s~-~.- - - - - - W TediK1011led1e
• Advanced Ja
Va P rogra mming (M SBT E) 4-8 8.Si~
n,e first constru t( ) method is used to connect this
s pecific serv Th ctor creates an unconnected socket. Later, the connec 'f' d port number at sp 'f• socket t
er. e second t ·t to the spec1 ,e ec, led i o
addre ss. Third co constructor creates a socket and connec s I . . te address on the specified r ntert'iet
Fourth nstructor creates a socket and connects it to the specified remo F"fth ernote Port
constructor creates a n unconnecte d socket but works for specified type of proxy. • const ructor creates .
unco nnected so k t . t a stream socket a nd connect 5 . an
. c e with a user-specified Socket/mp/. Sixth constructor _crea es . it to th
specified port n b k
h u m er on the named host. Seventh constructor creates a soc e t and connects 1t to t he specifled rernote
ost o n t he sp ecified remote port. The Table 4 .5 .1 shows the methods of class Socket. e

Table 4 ..
51
Description

void close( )
Method
void bi nd (SocketAddress bindpoint) Binds the socket to a local address .

Closes this socket.


------
-----
v oid connect(SocketAddress endpoint) Connects this socket to th e .se rve r.

void connect(SocketAddress endpoint, int timeout) --


Connects this socket to the server with a specified timeout
value.
SocketChannel getChannel{ ) Returns the unique SocketCha n nel object associated with this
-
socket, if any.
lnetAddress getlnetAddress{ ) Returns the address to which the so cket is conn ected.
lnputStream getlnputStream{) Returns an input strea m fo r t his so cket.
lnetAddress getlocalAddress{) Gets th e local add ress to whi ch the socket is bound .
in t getlocalPort{ ) Returns the loca l po rt numb e r to which this socket is bound.
SocketAddress getlocalSocketAddress( ) Returns t he address of the endpoint this socket is boun d to,
or null if it is not boun d yet .
OutputStream getOutputStream() Returns an output strea m for this socket.
int getPort( ) Ret urn s the remote port number to which this socket is
co nnecte d.

0 Sock etAddress getRemoteSocketAddress( ) Retu rn s t he address of t he endpoi nt this socket is co nnected

in t getTrafficClass( )
t o, or null if it is unco nnected .

Get s traffi c class or type-of-s ervice :n th e IP header for


-
packets sent from this Socket
--
bo ol ean isBound( )

boolean isClose~( )
Returns the bi nd ing state of th e socket.

Returns th e closed state of the socket.


--
-----
boolean isConnected( )

boolean islnputShutdown( )
Returns t he connection state of t he socket.
Retu rns whether the read-half of the socket co nnect10
closed.
~
----
. n is

ection is
boolean isOutputShutdown( ) Retu rns w hether the write-half of t he socket conn
closed.

Void sendurgent data (int data) Send one byte of urge nt data o n t he socket.

- - - - - - - - - - - - - - -- - - - - - - - - - - - -- - ~
i, ;~~
TE)
nce d Jav a Programming (MSB Networking Basics
{f_, Adva 4-9

Me tho d
. Oescription
int connecti~nTI , .int
ormancePreferences( me es for this socket.
~
"01d sVint band 'dth) Sets performance preferenc
w,
1atenc ,
~ (S~cketlmplFactory fac
) factory for the
staticvoid setSocketlmplFactory Sets the client socket implementation
application.
· the IP he ad er for
~f fic Cl as s( in t tc)
aJOI
sets traffic· class or type-of-servi·ce oct et m
ket.
packets sen t from this Soc
r-shu -- wnlnput( ) th is socket at "en d of st rea
m" ·
"d
aJOI
tdo Places the input str eam for
r- -- tdownOutput( ) for this socket.
Disables the ou tpu t str eam
,
"d shu
1/01
~ ing.
String toString( ) Converts this socket to a Str
,___ _--

te Client Application
4.5.1 Steps to Crea
nt applica t ion.
ss, let 's discuss the ste ps involved in creating a clie
ds of Socket cla
After discussing on me tho
ject.
//step I: Create a: So ck et Ob
Socket cjjent_ soc = ne w Sock et(servei~ poi"Lid);
ve~..
for co mm un ica tin g-with the ser
//step 2: Create I/O str eam s
));
ient_ soc.getlnputStre'a.m(
is = new Datalnp utStrea.in(cl
());-
(cl ient_ soc.geiOutputStream
os =new DataOutputStream
ete rs to ser ver.
1/ step 3: Send req ue st pa ram
ve r") ;
os.wnteUTF(''parameteJ" to ser
port~e.' ..
po nse an d r eceive the,res
II step 4: Wait for ·the s~rve r's res se_. res ponse wi·• l. l .he as Object instan ce)
JT T'T'C"/) -/tr u .becau
r.1.pec.'ll·st. in .Sll1nz:,, ,- . . · ,. . : ._ ·
·
=· rvll"lllg j 1s.Teau
/C' • ~J · u Lr ( . , f •;;
C '
vtrmg aJl~
_dQ~ .
II step 5:clos_e the socke t wh en
client_ soc.close( );

ets
4.6 TCP/IP Server Sock
This class is de fin ed as: .
· bt · a po rt and list en for·clie nt req ues ts.
r applicati on s to o am
This class is use d by ser ve
• ·ple~ en ts Ciose,a ble
. rSock et ex ten ds. Ob"~ect·.un
. .
public cla ss Serve a con nectio n req uest t o
. "t' acc ep t( ) me tho d. This me thod Lis ten s for
b t 5 erSocket. class
1s 1 5
ors of Serve rSocket class.
Th · ·.. · . how s the overloaded construct
ou erv
e notice able po int a acc t
ept s it. Following hS s
be made to this soc ket an d

· l. ServerSocke t()

2. ServerSocket(in t po rt)
3 ba cklog)
· ServerSocke t(in t port, int
. /ne tAddress bindAddr) ket ob jec t using accep
t( )
4 .
cke t. l ate r, clie nt binds to this soc se rve r
backlog, constructor cre ate s a
· Sen,erSocket(mt port, mt nd ser ver sobound to the specified po rt. hThi rd
s a n un bo u ve r socket, F with
The first constructor cre ate
.. k/ structor cre ate s a server
. h the spe c1f1ed bac og. ourt con
metho d T ate s a ser mb er w,t to.
secon d constructor cre
socket · he. ds it to t he spe cified local po rt nu
th and bin
' bin d ,.-.. M""'"'""
ad dre ss to -
a nd loc al IP
ified po rt, list en ba ckl og, Y l' U b lJ c a ti on s
Adv anc ed Jav a Prog ram min g (MS
- ~~•' -~~ ~~ ~~ ~~ ~~ ~~ ~~ BTE J_)_= = =~ ~~ 4-10=-= -=- =-=
-=- =-= -=- == == =;; ;i;;N;;;e~tw
~ o~rk:i~,,g
The Tab le 4 ·6 · 1 sho ws the met hod .... 1:3a~i
s of ServerSocket class . ~
Tab le 4.6.1 : Methods o f Se rverSocket class
Met hod oescription
Soc ket acc ept( )
·
liste ns for a conn ectio n to be mad e to this sock et a n d ~
void bind (Soc ketA ddre ss end poin epts it.
t)
Binds the Server sock et to a spec ific add ress (IP ad dr es ~
· Port
num ber) .
void bind (Soc ketA ddre ss end poin
t, int backlog) .
Bmds t he serv erSocket to a. spec ific add ress (IP ad dre ss~
Port
num ber) .
void close( )

Serv erSo cke tCh ann el getC han nel(


)
Closes this socket.
Returns the uniq ue Serv erSo cket Cha
------
nnel obje ct ass ocia ted ~
this socket, if any.
lnet Add ress getl netA ddr ess ()

int getl oca lPo rt( )


Returns the local addr ess of this serv
er sock et. --
Soc ketA ddre ss getlocalSocketA
Returns the port num ber on whic h
this sock et is listening . -
ddress( ) Returns the add ress of th e end poin
t t his sock et is boun d to, or
null if it is not boun d yet.
pro tect ed void implAccept(Soc
ket s) Subclasses of ServerSocket use this
m etho d to over ride accept()
to retu rn thei r own subcl ass of sock
et.
boo lean isBo und ( )
Returns the bind ing state of the Serv
erSo cket .
boo lean isClosed( )
Returns the closed state of the Serv
erSo cket .
void setP erfo rma nce Pref eren ces
(int connectionTime, Sets perf orm ance pref eren ces for
int late ncy , int ban dwi dth) this ServerSo cket .

stat ic void setS ock etfa ctor y(So


cket lmp lFac tory fac) Sets the serv er sock et imp lem enta
tion fact ory for the
appl icati on .
Stri ng toS trin g()
Returns the impl eme ntat ion addr
ess and imp lem entation port of
this sock et as a Strin g.
4.6 .1 Ste p to Cre ate Ser ver Program -
Afte r stud ying met hod s, lets disc
uss the steps to create a simp le serv
er prog ram in Java.
//st ep 1: Cre ate serv er sock et Obj
ect.
Soc ket servei:__ s oc = new Soc ket( serv
er, port_ id);
// step 2: acc ept clie nt requ rest
Soc ket cl_ soc = serv er_ soc. acc ept( );
//ste p 3: C reat e J/0 s trea ms .for com mun icat ing with the serv er.
is = new Dat ainp utSt rea m(cl_ soc.
getf nputStream ( ));
os = new Dat aOu tput Stre am( cl_ soc.
getO utpu tS trea m( }};
, Advanced Java Programming (MSBTE)
~ 4-11 Networking Basics
,J::::: (Stn'ng) is.readfJTF()· (ty,
i/fli1$ JIB • d
pecast in Strinu

-~
• A ply required logic and b • an pru-se 'val' in reqwi-ed dalatype)
// steP5: p . . respond hack to client.
,~ e[JTF(strmg type response to clieiu 1•
~
. close the sockets when done
tf steP6• •
d soc.dose();
~ ,er 50 c.close();
_.'{'f l -

Refer the TCP/IP client-server communicati


on programs from Section 4.11.

4.7 Class URL


class URL represents a Uniform . Resource Lo . · . .
. . cator, a pointer that refers a "resource" on the World Wide Web. A
ource can be a filI e or a d irectory, or 1t can be a f
res re erence to a query to a database or to a search engine.
Public final class URL extends ·
Obiect
J ·
im·p. ·
·
te' m ··.1·:1zabl. e .
·,. ·.eQ,t'iS·_·• s•en~
AURL can optionally specify a port numbe · t 0 h' h · ·
. . r, w IC the TCP connection is made. If the port is not specified then the
default port for the protocol is used.

There can be different forms of writing URL. Such as:

1. http://www.nagpuruniversity.org/links/Departments.htm

z. http://www.gujaratuniversity.org.in/

3. http://puchd.ac.in/

Following is the list of constructors of URL class :


1. URL(String spec)

Z. URL(String protocol, String host, int port, String file)

3. URL{String protocol, String host, int port, String file, URLStreamHandler handler)

4. URL(String protocol, String host, String file)

S. URL(URL context, String spec)


6- URL(URL context, String spec, URLStreamHandler handler)

The first form creates a URL object from the specified String. Second form creates a URL object from the specified
Protocol, host, port number, and file. Third form creates a URL object from the specified protocol, host, port number, fi le
and handler. Fourth form creates a URL from the specified protocol name, host name, and fi le name. Fifth form creates a
U~L by Parsing the given String spec within a specified context. Sixth form creates a URL by parsing the given String spec
th th
Wi e specified handler and context. ·

The Tabel 4. 7.1 shows the methods of java.net. URL class.

..
T ble 4 71 . methods of java.net.URL class
a
Description
Me.thod
oolea . , .
11 Compares invoking URLwith specified obj.
• equafs(Object obj)
ring
&etAuthority( ) Retrieves the authority part of invoking URL as String.
IJect Retrieves the contents of invoking URL.
&etcontent( )

• • Tet11Kaowled5e
· P u bl l t a t 1011 ~
... Advanced Java Programming
(MS BTE ) 4-12
~ ·
Networl<,i
t\~~ '
~ It~
oescriptfon ~
Object getCo
Method
ntent(Class classesl l)
int getDefaultPort
l)
\
Retrieves the con tents of this URL
Returns the default por t number of the protocol as
\invoking URL
;;\ ti
~i\~
~

String getFil el ) . of invoking URL


\Returns the file name
String getHostl )
Returns the host name of invoking URL
String getPathl )
Returns the path pa rt 0 f invoking URL.
int getPortl )
Returns the port number of invoking URL.
String gl!tProtocoll ) .
Returns the protocol name of · K U~
mvo mg .
String get Qu efv l )
Returns the query part of inv
oking URL.
String get Re fl)
Returns the refe rence of inv oki
ng UR L.
String get Us erl nfo l)
Returns the userlnfo part of
invoking URL.
int has hC ode l )
Returns an integer s~itable for
hash t able ind exing.
URLConnection openConn
ectionl) Returns an URLConnection ins
tance that represents a connec
the rem ote object . tion~
1 .
URLConnection openConn
ectionlProxv proxy) \same as openCo nnectio nl \, exc
ept that the connection will
through the spe cified pro xy. be m~
lnputStream openStream _
{)
Opens a connection to invoki
ng URL and ret urns an lnp
object to read fro m tha utltm\
t con nec tion .
bo ole an samefile{URL oth

i\
er)
Compares whether invoking
URL and spe cified URL shares
or not. · same
voi d set (St rin g pro toc ol,
String ho st, int port, String
file , String ref) Set s the fie\ds of the invoki
ng UR L. .
Str ing toExternalForm{)
Con st ructs a string repres en -
URI toU RI (} tat ion of inv oking \JRL.
Converts and ret urn s the inv -
String toS tri ng () oking URL int o a \JR\.
,co nve rts and ret urns the inv -
oking URL int o String .
Pr ogr am 4.7 .1 : Writ~ a program that dem
onstr ate the use of URL c\ass an
d ·•
import java.io.*; t,s methods.

import java.net. *;
class URLD emo
{
publi c sta tic void main (St
ring ar[ 1) throws lOExcep
tion .
{

String st :;;; " htt p://admissi


ons.p uchd.a c.in/"
if (st.length t = 1)
{

System. err .print ln (' usage


: jav a UR LD emo url'');
r
' U, ,Advanced Java Programming (MSBTE) 4-13 Netw orki ng Bas ics

~ retun1;
}
URL url = new UR L (st);
+
System. out. prin tln ("Authority :::: 11 url.getAuthorit ( )) .

. . Y '
Syst em. out. prm tln ( File = + UI·I .getF1le( )) .
11 11

. I (" Hos t = " + ·I H ,


System.out .prm t n II lU .get Ost( )) ;
. . •
p h
Syst em. out. pnn tln ( Pat h = " +ur l .get at ());
·tP (
Syst em. out. prin tln ("Port = " +ur l .ge 011 ));
I P
System. out. prin tln ("Protocol :::: " + ur .get roto col( )) .
System.out. prin tln ("Query = ." +ur .ge uery ));
l tQ.· (. · '

tRe f( )) ;
System.out. prin tln ("Ref= " +ur l.ge
System. out. prin tln ("U ser Info = " +ur l .ge tU serIn£.o( ));
System.out. prin t ('\n');
InputStr eam is = u.rl.openStream( ) ;
int ch;
while ((ch = is .rea d ( )) != -1)

System.out. prin t ((char) ch) ;


is.close ( );
}

Input:

Input URL is http :/ /adm issi ons .puc


hd .ac.in/

Outp ut :

o .jav a
:'-.jd 1~1 .3\.. bin }jav a.c URLDem
URLDe1!1O .
C:,j ctk 1.3 ,bin >ja1,1a sion s.pu c hd. ac .1.n
Aut hoP ity = ad1 11is
ile = / in
ost ~ adm issi ons .pu chd .ac.
ath = /
Poi• t = -1
1•oto co 1 = ht tp
Que py = nul l
Ref = nul l
sei- Info = nul l
<?DOCI\:'PE htm l PUB LIC "-//W
3<;!/-'.'D TD x:r:~/-0 T1: ans itio nal/ .lEN " ." htt p:/ /
m-m .w3 .op

:t ~i9 9J/x htm l ">


/IR/ xht1 11l1 /DID /x}1 tml 1-tr ans
J.oi g le>
<htm l xml ns= ''htt p:// 'l•m w.w . ~ _ Pari jab Un ivel "sit y, ,Cha ndig ~1•h ~ Ind ia{ /tit
hE:a d) . . . 'lku zpF SdJ CPE uRJ BnH 0" /)
uss1 on.> t="x U0g 1s-3 e" / )
<t i tle> Un1 ve1• s1.ty Ad1 yID " con te~ =iso -··88 59-1="te " J1tt p-eq uiu ="c ont ent -typ
<1T1eta na111e ="a lexa Ue: .-if typ e xt.l e ss " J1i-e f """ • • / in c lud es/s tan da
:?!a l'Sie she et"
lllf:t a con ten t ="t ext /htm l;
l- st .Y - Pan j ab Uni ve1 •sit y ,. Ch
11.nk titl e=" Sta nda :rd" !:"e t=" Uni vel' sity Adm issi ony,s De ai>t:Jflef_lts, Cot~ 1•se s., s
•d.c ss" /) c<? nt~: it.Y , Cha ndi aPh , Pac ult
me ~a nam e= " d e sci• ipti on" uei •
nd1.gai-}1,. Ind ia, Pan jab u,n m() met h 0 d
e data as a byte seq ue nce , and t his is bec aus e of openStrea ·
At the . ·
reso urc
end , this pro gram sho ws the
. --
--------------.- " Tethl lno1111 e4Je
Publ l c a t ilJIIS
4-1!
ing (MSB TE)
Y Advanced Jav a Progra mm
e insta nee
n ection cla ss sta .rts . Th
UR L C on ss is an ab straOf
nection Of rting it locally. This cla
4. 8 Class URLCon rver the rol e ct
the rem ote se ' ct pri.or t O tra ns po.
. bJ'e
nnection to . the remote o
Once a clie nt make s co
·
Of
examines the pro pe rti es
URLConne cti on class
class and it is de fined as: ork. T••·
. . "th th e URL ov er th e netw ..a of
on ex te nd s Objec t un 1c ati ng w1 is us ed t
LC on ne cti cf1on ( ) me th od 0 create
pu bli c ab slr ac l cla ss UR hOd tha t allow co( mm
s ) The 0 penConne te ob jec t
t
Th e URLCon necti on
class contains many me. ( ) and connect · ction to t he rem o ·
ct ion .
methods are openConn
e
. d to make conne
the comm only used d is use
URL. The connect( ) metho
co nnectio n object on a
URL
Create Connection to
4.8.1 Multistep Process to
ste ps included are:
s. Th e
ect ion to a URL is multi step proces URL.
Cr eat ing a co nn
. C ec tio n( ) metho d on a
ing the open on n
ject is cre ate d by invok
//S tep 1 : co nn ec tio n ob
ttp s://msbte.org.in/") ;
UR L url = new URL("h
);
= url.openConnection(
URLC on nection co nn
are ma nip ula ted .
pa ram ete rs an d ge ne ral req ue st properties
//S tep 2 : se tup
tln pu tS tre am ( ));
tre am dis = ne w Da tal np utS tr~ (co nn .ge
Da tai np utS t( ) me tho d.
the rem ote ob jec t is made, us ing _the conn ec
tio n to
//S tep 3: ac tua l co nn ec
co nn .co nn ec t() ; ing an y ite ra tiv e sta tem
en t.
oh jec t us
he ad er fie lds an d the contents of the remote
//S tep 4: ac ce ss th e

wh ile ( (String inp utL ine


= dis.readLine( )) ! = null)
{
pu tL ine );
Sy ste m. ou t.p rin tln (in

}
str ea m connection.
//Step 5: do se the of I/0
dis .cl os e() ; . ·
functions tha t aff ect t he invok·ing o b'Ject of this class.
the me mb er
The Table 4.8 .1 enlists

Method
Table 4.8.1

Description ---
---
.
rop ert y(S tring ke y, Adds the specified key and va1ue as req ue st p ro pe rty .int o th e invoking obJec t.
void addRequestP
String value)

abstract void connec


t( ) Opens an d connects a
link t 0 th
e res ou rce ref ere nc ed by inv oking o Je
------
b' ct' for
co mmunicatio n.
-- --
ord i tnls
s acc ng to the us er .int era cti on pe rm iss ion given to
rlnteraction( ) Re tur ns bob.olean value
boolean getAllowUse . k'
invo 1ng o Ject.
timeo ut tim e.
int getConnectTimeo
ut( ) Returns t he co nn ectio n
need Java Prog ramm ing (MSBTE)
gJ - Method
r---.
4-15
--
Networkin g Basics

Desc ription
~ tent() ·
Ret rieve s the c
ontents of Invoking objec t.
~ teontentEncoding( ) Retri eves th e St . g of Invok ing obje ct.
strlllS ge nng represe nting th e content~en codln
i cantentLength( ) Retu rns the len h
int get gt of content of Invoking objec t.
1
teontentlengthlong( ) Returns the len th
1<1118 ge g of content as long argum ent.
, getContentType( ) Returns the cont
51rtn8 ent type, set for the invoking object.
th
, e
!011! getDate( ) Retu rns the d at e on whic h the conn ectio n Is made as long. Actua lly ret urns
. .
milliseconds th t are passed since midn ight Janu ary 1, 1970 GMT.
a
.
I lean getDolnput( ) Returns the b 00 1
ean value of doin put flag of invok ing objec
t.
~
t,oalean getDoOutput( )
.
Returns the bo oIean va 1ue of doou tput flag of invoking obJ ect .
t he
Expiration( ) the curre nt objec t. Actua lly returns
~ R~t~rns the expiration date set for e.
1970; after which it is going to be expir
mrll,seconds since midn ight January 1,
L-- -
number.
/String getHeaderField(int n) Returns the value of specified header
name .
String getHeaderField(String name) Returns the value of specified header
from invoking obje ct's open co nnect ion.
linputStream getlnputStream( ) Returns the lnputStream object that reads
ight
he millisecon ds since midn
/long getLastModified( ) Returns the last modified date. Again returns t
I January 1, 1970 .
ectio n.
I writes t o invoking object's open conn
outputStream getOutputStream( ) Returns the Outp utStream objec t that
of
ains the perm ission relat ed attribut es
1

Permission getPermission( ) Retu rn s t he Perm ission objec t that cont


invoking obj ect.

Ret urns the value of invok ing object's


URL field.
URL getURL( )
of invoking object.
Set s th e boolean value of doinp ut flag
void setDolnput(boolean doinput)
of invoking object.
Sets t he bool ean value of doou tput flag
void setDo0utput(boolean dooutput)
ing obj ect.
Returns a String re presentat ion of invok
!ing toString( )
tion and IOException.
ection class throws MijlformedURLExcep
Note: The methods inclu ded in URLConn
n class methods.
Program 4.8.1 .· . th t demonstrates the use of URLConnectio
Write a program a

·
· ·0. >-<;
illlport Java.1
·
iinport Java.net.*;
iOJport ·
Java.util.ArrayList;
iniport ·
Java.util.Date;
illlport ·
. Java.u til.HashM ap ;
1
lllpor1 ·
. Java.util.List;
illlpor1.
Java.u til.Map;
PUhLc I .
~ RLConnectionDem o
- l)11
Teda Knotuledgi
Pub /Jr atton s
V


Advan ced Java Programming (MSBTE)

(iii) datagram size


.
(1v) n d packe ts of data (datagram) ove
checks um that are use d to se
. ut effective classes r
Theja va. net packag e provid es a few simple b
a netwo rk, preferably using UDP. They are :
(i) java.n et.DatagramPacket
(ii) java.net.Data gramSocket
in detail.
. . n of these three classes
Follow ing Section 4 .9.1 describes the apphca tio

4.9.1 java.net.DatagramPacket
ection less datag ram delivery
d is responsible for con n
The DatagramPacket is a final class of java.n et package an
service . The signat ure of this class is:

public final class Datag ramPa cket exten,d s Objec t . d d.


. d t he packe ts are route accor ing t o these
.
As mentio ned above , each data packet contains heade r inform ation an
inform ation. As we mentjo ned, the delivery of these packets d arid even diffe rent packe ts sent from one
is not guaran tee .
machi ne might be delivered through different routes .
Follow ing is the list of Datagram Packet constr uctors .
1. DatagramPacket(byte[ Jbut int /en)
2. DatagramPacket(byte[ Jbut int /en_, lnetAddress address, int
port)
3. DatagramPacket(byte[ J but int offset, int /en)
4. DatagramPacket(byte[ Jbut int offset_, int /en, lnetAddress addres
s, int port)
5. DatagramPacket(byte[ Jbut int offset, int /en, SocketAddress
addre ss)
6. DatagramPacket(byte[ Jbut int /en, SocketAddress addre ss)
The first constructor create s a DatagramPacket object that
receives t he packet s of specif ied le ngth in specified byte
array. Second constructor create s an object that sends the
datagr a m packe ts of specif ied length at specif ied port number
of specified addres s. Third constructor create s a DatagramPac
ket for receiving packe ts of length Jen a nd specifyi ng an
offs et int o t he buffer . Fourth constrµctor create s a Datagram
Packet obje ct fo r sendin g packe ts of length /en with offset
th e specifi ed port numbe r on the specified addres s. Fifth const to
ructor create s a Datag ram Pa cket o bject for sending
of length /en with offset t o the specified socket addres s. Sixth packets
const ructor constr ucts a Datag ra m Packe t o bje ct sendin
packe ts of length fen to the specified port numbe r of t he specifi g the
e d socket add ress.
The Table 4 .9.1 shows the metho ds related to java.net.Dat agram
Packet class.

Table 4.9.1 : Methods related to java.net Datag ramPa


cket class
M ethod ~

lnetAddress getAddress( ) Descr iption


__.:..
Return s t he IP addre ss of t he destin atio n mach ine to
which the
invoking datag ram packe t is going t o be del ive red o r from
which the
datagr am was receiv e d.
byte[ ] getDa ta( )
Return s the data buffer as byte array. -----
int getlen gth( )
Ret urns t h e lengt h of the dat a t o be se nt o r receiv ed by
object .
---
the invoki ng

---
int getOffset ( )
Re~urn s th e offset of t he dat a to be sent or rece ived by
obJect . the invoking
r
dvanced Java Programming (MSBTE) . Networking Basics
~
4-19
~ ---=:::::::::::_
---
Method
~ DescrJption
() ·
~ Retu rns the Port number of the network host to which datagram ,s
t.
being sent or from where it is received by invoking objec
~ dress getSocketAddress( ) IP address a nd
Retrieves the SocketAddress object (a comb inatio n of
t is being sent
port number) of the network host that invok ing packe
to or corning from .
~ ddress(lnetAddress iaddr) which invoking
vor Sets the IP address of the network machine to
datag ram is to be sent.
~ Data(byte buf[ ))
VOi Sets the specified data buffer fo r invok ing object.
~ tData (byte buf[ ], int offset, int length) Sets the specified data buffer for invok ing object
with specified
offset and length .
~ etLength(int length) Set the length for invok ing packet.
~ setPort(int port) the invoking
Sets the port number on the network host to which
datagram object is being sent.
network host to
~ dsetSocketAddress(SocketAddress address) Sets the specified SocketAddress object of the
which invok ing datagram object is being sent.

4.9.2 java.net.DatagramSocket
ng and
ge and repre sents a connection-less socket for sendi
The Datag ramSocket class is defi ned in java.net packa delivery or
is no guarantee of its conte nt, sequence of content,
receiving datagram packets. As mentioned above, there
delivery time. This class is defi ned as:

publi~ ~l~ss)Jatagn1,tnS06k~t,hten ds Obj~ct,implenie


nts ¢1;~¢~Ir .
ing and
lly, an object of this class represents a socket fo r send
Note that, this class is not defined as fi nal class. Actua
ructors of this class :
receiving datagram packets. Following is the list of const

1. DatagramSocket()
pl imp/)
2. protected OatagramSocket(OatagramSocketlm

3. protected OatagramSocket(int port)


s laddr)
4. protected OatagramSocket(int port, lnetAddres
bindaddr)
5. protected Oata gramSocket(SocketA ddress
local machine.
First constructor creates a DatagramSocket objec
t that can be connected to any available port on the
can be
object which is with specified Socket/mp/ object that
ocket
Second constructor creates an unbo unded DatagramS port numb er of local
tructo r constructs a DatagramSocket and connects it to speci fied
..
irnpleme nted as requi.re d. Th.,rd cons . . .. ss and its
object that 1s 1n1t1ally connected to spec1f1ed IP addre
machine F h constructor crea t es a DatagramSocket specified SocketAddress
specified
· ourt
· . ct reates a Datag ramS ocket object that is connected with
Port number. Ftfth constru or c
Object,

The Table 4.9. 2 showing meth ods of this cl;;)ss.


Table 4.9.2 : Methods of this class
I'-- _ Description
t-- -_ M~thod
. h . king Datag ramSo cket object speci fied SocketAdd
ress object ·
~Oid b' nd Binds t e mvo
' (SocketAddress addr)
~o· Closes the invoking DatagramSocket object.
Idclose( )
'!!!1-i.,,. TethKnowled 0
~ ~ P ub l l cat lO ~ 'i
'(,, Advanced Java Programming (MSBT E) 4-20 \! ~~~it~
o escript'ton
.._,,
Metho d ~
void connect(lnet . ith 'fed IP address and port number. ~ :
int port)
Address address, Co nnects the invoking ob1ect w · spec,'
ilil
.
void connect(SocketAddress addr)
Connects the invokm. g O bl e ct with spec\fed
'
socketAddress object .
P'
void disconnect( ) Disconnects the Invoking socket object . {
DatagramChannel getChannell ) Returns the DatagramChannel O b'Jett related with invoking DatagramSocl<.et ob·
let\,
lnetAddress getlnetAddressl ) Returns the IP address to which . . king object is currently conne cted.
mvo
lnetAddress getlocalAddressl ) Retrieves the internet address to wh'1ch invoking object is currently connected

int getloc alPort l ) .
Retneves the port num ber of the local host to which invoking object is connected
.
SocketAddress .
Retnev es the loca1socket address to which invoking object is conne cted.
getlocalSocketAddressl )

int getPo rt( ) Returns the port number to which invoking socket is conne
cted .
SocketAddress Returns the address of the remote socket to which th e invoki
getRe moteS ocketA ddres s()
ng object is connett~I!
to or returns null if unconnected .
boole an isBound( ) · Returns the binding st.a te of the invoking socket as boole
boole an isClosed( ) Returns wheth er the invoking socket is closed or not.
an value.
\
boole an isConnected( ) Returns the connection stat e of the invoking socke t object
\
void receiv e(Data gramP acket pkt) Receives a datagr am packet from a socket object .
.
\
void send( Datag ramPa cket pkt) Sends a datagr am packet using invoking socket object .
\
\
4.9.3 Sending and Receiving Data Packets using Datagram
Socket and DatagramPacket
The Datag ramSo cket and DatagramPacket classes are
used for conne ction- less socket t)rogr ammi ng. let's discuss
steps and proce dures to send and receiv e data packe t
ts using t hese classe s with an example .
4.9.3 (A) Send ing DatagramPackets using DatagramSock
et
To send data via Java's Datag ramSo cket you must first create
a DatagramPacket. \-\ere is how that is done:
byte buffer[] = new byte[65508];
InetA ddres s addr = lnetAddress.getByName("www.unipune.ac.in");
DatagramPacket pkt= new DatagramPacket(butter, buffer.\eng
th( ), addr, 9000);
The byte array is the data that is to be sent in the UDP datagr
am. 1he length gi\ien t o the OatagramPacket cc
is the length of t he data in the buffer to send. All data in
the buffer after this length will be ignored.
The addr Is the objec t of ln etAddress that contains the
address of the machine to send the \JOP packet t <
numb er is 9000. UDP and TCP ports are not the same.

To send the DatagramPacket we must create a DatagramSo


cket which is targe ted at sendi ng data. \-\ere i~
done:

DatagramSocket ds = new DatagramSocket( );


After doing all required settings, to send data call the send\)
method, like this:
ds.send(pkt);
~~~~~~~~~~~~~~~~==='."".:::~;;::;;::~:~~~~=~~~:~
V
Ne two rking 13

Advan ced Jav a Progra mm 4-22 gra mP ack et has no info rrn
ing (MSBTE) - h oat ar1..,.
Notice hOW t ~ data. Thi vi"\ ab
Second , a byt e buff J and d is created. s is bec aus e we are goin
a DatagramPacket P tag sending a d l:lllt
<\~i~
romPocket for . atio n add d &to l.t
the nod e to send dat a t o, eating a OO res s is nee e ·
as It does w hen er
t h e Dat agr am Packet for rec d' Therefore no dest1n · s~
eiving data, no t for sen ing, ·ved
. 1 ate d in the Da tag ram
1s oc Pa ck
he data recei · et's b ,
Fin ally, t he Da tag ramSoc hod is called . T 'ft~
ket's recelvel ) met
buf fer . Thi s buf fer can be
obtained by calling: . . ·
byte bu f[] = pkl .ge LData( );
4 .10 Diffe rence between TC
P and UD p
Sr. UDP

-------
No. TCP
.. .. . ctionless pro toc
1. TCP is a connection-orien UDP is a conne ol.
ted protocol.

------
2. TCP hea der size is 20 UDP Header size is 8 bytes
bytes. ..
3. TCP does err or checking wit UDP - hecking bu t no recove
h recovery option . does err or c , · ry o pti on s.
4. The speed for TCP is slowe

--
r tha n UDP. The speed of UDP is fas ter
tha n TCP .
5. TCP guarantee t he data tran
sferred remains intact
UDP does not guarantee tha
t the me ssages or pac ket
and arr ives in the same ord s sent would
er in which it was sent. reach at all.
6. TCP rearranges data packet
s in the specified.order. UDP has no specified ord er, as all pac ket
oth er. In a case wh en ord
s are ind epe nde nt of each
erin g is req ui red , it is
ma naged by the
- }
application layer.
7. TCP is sui ted for applica
tions tha t require high UDP is suitable for
reli abi lity and wh ere the app lica tion s that nee d fas t
and efficient
F
transmission tim e is transmission. Such
rela tively less critical. as, onl ine gam es and m
any ser ver s that answ er
small queries fro m huge num iI
ber s of clie nts .
8. HTTP, HTTPs, FTP, SMTP,
TCP prot oco l. o
Telnet are examples f DNS, DHC
P, TFTP, SNMP, RIP, VOi P
are exa mp les of UDP pro
11
t ocol.
C
4.1 1 Im po rta nt Program
s on Sockets {

. In t his sec tion we wil l discuss some imp


ort ant programs on TCP/IP
dif fer ent com mand pro mp soc ket • . Re
ts. First run server progra pro gra mm ing m em ber to open two
m and the n (in se d
con com ma nd pro m pt) .
Pro gram 4.11.1 : run che nt pro gra m.
Write a TCP client-server
program· the cl' t
server, th e server returns · •en accept
the factorial of that n b s a number fro m the user and sends it to the
.
um er to the che
Fil e 1 : ClientProg .java nt.

impor t ja va.net .*;


imp ort jav a .io.*;

imp ort jav a.u til. Sca nne r;

class Cli en lProg


{

public sta tic void ma in(Str


ing ar[ ]) th . IO E
{ IOW S xce pl'
ion

You might also like