Professional Documents
Culture Documents
4 .2.1 Client - Server: P Art1
4 .2.1 Client - Server: P Art1
..:.,. 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.
Table 4.2.1
________ ~
_:· -
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.
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.
(iii) Th e first 8 bits (first byte) defines the netid and the rema ining 24 bits (3 bytes) defines the ho_s tid.
(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.
(il) The fi rst 24 bits defines the netid an d remaining 8 bits defines the hostid.
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
Table 4.3. 2
Interfaces '
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.
class FactoryMethodsDemo
ception
. (Stri' ncro a:r[ ]) thro~s UnknownHostEx
pu bli c stati.c vo1 mam
'd
InetAddress add r3 [ 1- ne
t
for (int i = O; i <ad dr3. leng b; 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
3. String getHostAddress()
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.
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
C: \jdk1. 8\bio> .
(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
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 .
in t getTrafficClass( )
t o, or null if it is unco nnected .
boolean isClose~( )
Returns the bi nd ing state of th e socket.
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( )
-~
• 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 -
1. http://www.nagpuruniversity.org/links/Departments.htm
z. http://www.gujaratuniversity.org.in/
3. http://puchd.ac.in/
3. URL{String protocol, String host, int port, String file, 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. ·
..
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\~
~
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 .
{
~ 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
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)
Input:
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
}
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)
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
·
· ·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)
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:
---
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:
1. DatagramSocket()
pl imp/)
2. protected OatagramSocket(OatagramSocketlm
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.
-------
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 {