Ad. Java Unit - II PDF

You might also like

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

Chapter 2

Network Programming using JAVA


Objective: This chapter introduces basic knowledge on Networking and its principles such as
Sockets, client-server concept, etc required to write networking programming using JAVA.
Simple eample programs are given to understand the !low o! program to access the socket !or
reading and writing data !or it.
Outcome: The readers will be in a position to understand the Sockets in Networks and to write
JAVA programming !or Socket "#$.

2.1 ntro!uction to Networking an! "ockets
2.1.1 "ocket Overview
A network socket is the same as an electrical socket. Various plugs around the network have a
standard wa% o! delivering their pa%load. An%thing that understands the standard protocol can
&plug in' to the socket and communicate. The same idea applies to network sockets, ecept that
we talk about T()#") packets and ") addresses rather than electrons and street addresses. "nternet
)rotocol *")+ is a low-level routing protocol that breaks data into small packets and sends them to
an address across a network, which does not guarantee to deliver said packets to the destination.
Transmission (ontrol )rotocol *T()+ is a higher-level protocol that manages to robustl% string
together these packets, sorting and retransmitting them as necessar% to reliabl% transmit %our data.
A third protocol, ,ser -atagram )rotocol *,-)+, sits net to T() and can be used directl% to
support !ast, connectionless, unreliable transport o! packets.
2.1.2 C#ient$"erver
The term client#server mentioned in the contet o! networking and a server is an%thing that has
some resource, which can be shared. There are computer servers, which provide computing
power, print servers, disk servers and web servers. A client is simpl% an% other entit% that wants
to gain access to a particular server. The interaction between client and server is similar to the
interaction between a light and an electrical socket. The power grid o! the house is the server and
the lamp is a power client. The server is a permanentl% available resource, while the client is !ree
to &unplug' a!ter it is has been served. "n .erkele% sockets, the notion o! a socket allows a single
computer to serve man% di!!erent clients at once as well as serving man% di!!erent t%pes o!
in!ormation. This !eat is managed b% the introduction o! a port, which is a numbered socket on a
particular machine. A server process is said to &listen' to a port until a client connects to it. A
server is allowed to accept multiple clients connected to the same port number although each
session is unique. To manage multiple client connections, a server process must be multithreaded
or have some other means o! multipleing the simultaneous "#$.
%eserve! "ockets
-uring establishing socket based connection !rom the client to server, a higher-level
protocol ensues that is dependent on which port the application or the user uses in his
program. The T()#") reserves the lower /,012 ports !or speci!ic well-known protocols.
3ost o! these protocol seem !amiliar to all i! %ou have spent some time sur!ing the
"nternet. 4or eample, port number 1/ is !or 4ile Trans!er )rotocol *4T)+, 15 is !or
Telnet, 16 is !or e-mail, 78 is !or !inger and 90 is !or :%per Tet Trans!er )rotocol
*:TT)+. "t is up to each protocol to determine how a client should interact with the port.
4or eample, :TT) is the protocol that web browsers and servers use to trans!er
h%pertet pages and images. "t is quite a simple protocol !or a basic page-browsing web
server. ;hen a client requests a !ile !rom an :TT) *;eb Server+ server, an action known
as a hit happens, it simpl% prints the name o! the !ile in a special !ormat to a prede!ined
port and reads back the contents o! the !ile. The server also responds with a status code
number to in!orm the client whether the request is !ul!illed and wh%. Sa% !or an eample,
i! a client requesting a single !ile, $in!e&.htm# and the server repl%ing that it has
success!ull% !ound the !ile and is sending it to the client. .elow the interaction between
clinet and server is shown !or better understanding the concept.
"erver C#ient
<istens to port 90. (onnects to port 90.
Accepts the connection.
=eads up until the second end-o!-line *>n+.
Sees that ?@T is a known command and that
:TT)#/.0 is a valid protocol version.
=eads a local !ile called #inde.html.
;rites &?@T #inde.html
:TT)#/.0>n>n'.
;rites &:TT)#/.0 100 $A>n>n'. &100' means &here comes the !ile.'
(opies the contents o! the !ile into the socket. =eads the contents o! the !ile and displa%s it.
:angs up. :angs up.
The above eample shows an actual transaction that %ou could have with an% web server near %ou
using :TT) )rotocol.
Pro&' "ervers
A pro% server is an intermediate server, which speaks between the client side o! a protocol and
server side socket protocol. This is o!ten required when clients have certain access restrictions in
an organiBation or an educational institutions. Thus, a client would connect to a pro% server,
which does not have such access restrictions and the pro% server would in turn communicate !or
the client. A pro% server has the additional abilit% to !ilter certain requests or cache the results o!
those requests !or !uture use. A caching pro% :TT) server can help to reduce the bandwidth
demands on a local networkCs connection to the "nternet. ;hen a popular web site is being hit b%
hundreds o! users, a pro% server can get the contents o! the web serverCs popular pages once,
saving epensive internetwork trans!ers while providing !aster access to those pages to the
clients.
The interesting part about this sample program is that it is both a client and a server. To serve
certain pages, it must act as a client to other servers to obtain a cop% o! the requested content.
"nternet Addressing ever% computer on the "nternet has an address. An "nternet address is a
number that uniquel% identi!ies each computer on the Net. $riginall%, all "nternet addresses
consisted o! 51-bit values. This address t%pe was speci!ied b% "nternet )rotocol, version 2 *")v2+.
:owever, a new addressing scheme, called "nternet )rotocol, version D *")vD+ has come into
pla%. ")vD uses a /19-bit value to represent an address. Although there are several reasons !or and
advantages to ")vD, the main one is that it supports a much larger address space than does ")v2.
4ortunatel%, ")vD is downwardl% compatible with ")v2. (urrentl%, ")v2 is b% !ar the most widel%
used scheme, but this situation is likel% to change over time. .ecause o! the emerging importance
o! ")vD, Java 1, version /.2 has begun to add support !or it. 4urthermore, !or the net !ew %ears,
")v2 will continue to be the dominant !orm o! addressing. There are 51 bits in an ")v2 ") address
and we o!ten re!er to them as a sequence o! !our numbers between 0 and 166 separated b% dots
*.+. This makes them easier to remember, because the% are not randoml% assignedEthe% are
hierarchicall% assigned. The !irst !ew bits de!ine which class o! network, lettered A, ., (, -, or
@, the address represents. 3ost "nternet users are on a class ( network, since there are over two
million networks in class (. The !irst b%te o! a class ( network is between /81 and 112, with the
last b%te actuall% identi!%ing an individual computer among the 16D allowed on a single class (
network. This scheme allows !or hal! a billion devices to live on class ( networks.
(omain Naming "ervice )(N"*
The "nternet wouldnCt be a ver% !riendl% place to navigate i! ever%one had to re!er to their
addresses as numbers. 4or eample, it is di!!icult to imagine seeing &httpF##/81.8.8./#' at the
bottom o! an advertisement. Thank!ull%, a clearinghouse eists !or a parallel hierarch% o! names
to go with all these numbers. "t is called the -omain Naming Service *-NS+. Just as the !our
numbers o! an ") address describe a network hierarch% !rom le!t to right, the name o! an "nternet
address, called its domain name, describes location o! a machine in a name space, !rom right to
le!t. 4or eample, www.b!u.ac.in is in the A( domain and www is the name o! the speci!ic
computer that is a web server.
2.1.+. Java an! the Net
Java supports both T() and ") *T()#")+ b% etending the alread% established stream "#$
inter!ace and b% adding the !eatures required to build "#$ obGects across the network. Java
supports entire !amil% o! both the T() and ,-) protocol. ;hile T() is used !or reliable stream-
based "#$ across the network and ,-) supports a simpler, hence !aster, point-to-point datagram-
oriented model. The networking classes and inter!aces contained in the Gava.net package are listed
below in Table 1./
,ab#e 2.1 ,he C#asses an! nter-aces in java.net
Authenticator "netSocketAddress Socket"mpl
(ontent:andler Jar,=<(onnection Socket)ermission
-atagram)acket 3ulticastScoket ,="
-atagramSocket Net)ermission ,=<
-atagramSocket"mpl Network"nter!ace ,=<(lass<oader
:ttp,=<(onnection )asswordAuthentication ,=<(onnection
"netAddress ServerSocket ,=<-ecoder
"ndet2Address Socket ,=<@ncoder
"netDAddress SocketAddress ,=<Stream:andler
2.1.. netA!!ress
The "netAddress class is used to encapsulate both the numerical ") address and the domain name
!or that address. ;e interact with this class b% using the name o! an ") host, which is more
convenient and understandable than its ") address. The "netAddress class hides the number
inside. The "netAddress can handle both ")v2 and ")vD addresses. T:@ JAVA <".=A=H
2.1./ 0actor' 1etho!s
The "netAddress class has no visible constructors. To create an "netAddress obGect, %ou have to
use one o! the available !actor% methods. 4actor% methods are merel% a convention whereb%
static methods in a class return an instance o! that class. This is done in lieu o! overloading a
constructor with various parameter lists when having unique method names makes the results
much clearer. Three commonl% used "netAddress !actor% methods are listed below.
static "netAddress get<ocal:ost* + throws ,nknown:ost@ception
static "netAddress get.%Name*String hostName+ throws ,nknown:ost@ception
static "netAddress I J getAll.%Name*String hostName+ throws ,nknown:ost@ception
The get<ocal:ost* + method simpl% returns the "netAddress obGect that represents the local host.
The get.%Name* + method returns an "netAddress !or a host name passed to it. "! these methods
are unable to resolve the host name, the% throw an ,nknown:ost@ception. $n the "nternet, it is
common !or a single name to be used to represent several machines.
The !ollowing eample prints the addresses and names o! the local machine and two well-known
"nternet web sitesF
## -emonstrate "netAddress.
import Gava.net.KL
class "netAddressTest
M
public static void main*String argsIJ+ throws ,nknown:ost@ception M
"netAddress 3%Address N "netAddress.get<ocal:ost*+L
S%stem.out.println*3%Address+L
3%Address N "netAddress.get.%Name*Owww.bdu.ac.in O+L
S%stem.out.println*3%Address+L
"netAddress S;IJ N "netAddress.getAll.%Name*Owww.csbdu.in O+L
!or *int iN0L iPS;.lengthL iQQ+
S%stem.out.println*S;IiJ+L
R
R
:ere is the output produced b% this program.
de!ault#10D./29.108./59
www.bdu.ac.in #/89.26.12./D1
www.csbdu.ac.in#D2.12/.159./65
The "netAddress class also has several other methods, which can be used on the obGects returned
b% the methods Gust discussed. "nternet addresses are looked up in a series o! hierarchicall%
cached servers. That means that %our local computer might know a particular name-to-")-address
mapping automaticall%, such as !or itsel! and nearb% servers. 4or other names, it ma% ask a local
-NS server !or ") address in!ormation. "! that server is not having a particular address, it can go
to a remote site and ask !or it. This can continue all the wa% up to the root server, called "nterN"(
*internic.net+. This process might take a long time and so it is wise to structure %our code so that
%ou cache ") address in!ormation locall% rather than look it up repeatedl%. "n Table 1.1, the
most commonl% used methods are listed.
,ab#e 2.2 1etho!s o- netA!!ress
%eturn ,'pe 1etho! Name
boolean equals*$bGect other+
b%teIJ getAddress*+
String get:ostAddress*+
String get:ostName*+
boolean is3ulticastAddress*+
String toString*+
"nternet addresses are looked up in a series o! hierarchicall% cached servers. That means that the
local computer might know a particular name-to-")-address mapping automaticall%, such as !or
itsel! and nearb% servers. 4or other names, it ma% ask a local -NS server !or ") address
in!ormation. "! that server doesnCt have a particular address, it can go to a remote site and ask !or
it. This can continue all the wa% up to the root server, called "nterN"( *internic.net+. This process
might take a long time, so it is wise to structure %our code so that %ou cache ") address
in!ormation locall% rather than look it up repeatedl%.
2.2 ,CP$P C#ient "ockets
T()#") sockets are used to implement reliable, bidirectional, persistent, point-to- point and
stream-based connections between hosts on the "nternet. A socket can be used to connect JavaCs
"#$ s%stem to other programs that ma% reside either on the local machine or on an% other machine
on the "nternet. There are two kinds o! T() sockets in Java, where one is !or servers and the other
is !or clients. The ServerSocket class is designed to be a &listener,' which waits !or clients to
connect be!ore doing an%thing. The Socket class is designed to connect to server sockets and
initiate protocol echanges. The creation o! a Socket obGect implicitl% establishes a connection
between the client and the server. There are no methods or constructors that eplicitl% epose the
details o! establishing that connection. The two constructors used to create client sockets is shown
in Table 1.1
,ab#e 2.2 C#ient "ocket Constructor
1etho! Name %emarks
Socket*String hostName, int port+ (reates a socket connecting the local host to the
named host and portL can throw an
,nknown:ost@ception or an "$@ception.
Socket*"netAddress ipAddress, int port+ (reates a socket using a preeisting "netAddress
obGect and a portL can throw an "$@ception.
A socket can be eamined at an% time !or the address and port in!ormation associated with it, b%
use o! the !ollowing methods as given in Table 1.5
,ab#e 2.+ C#ient "ocket 1etho!s
1etho! Name %emarks
"netAddress get"netAddress* + =eturns the "netAddress associated with the Socket obGect.
int get)ort* + =eturns the remote port to which this Socket obGect is
connected.
int get<ocal)ort* + =eturns the local port to which this Socket obGect is connected
$nce the Socket obGect has been created, it can also be eamined to gain access to the input and
output streams associated with it. @ach o! these methods can throw an "$@ception i! the sockets
have been invalidated b% a loss o! connection on the Net. These streams are used eactl% like the
"#$ streams to send and receive data. The Table 1.2 shows the methods
,ab#e 2.. "ocket $O "tream 1etho!s
1etho! Name %emarks
"nputStream get"nputStream* + =eturns the "nputStream associated with the invoking socket.
$utputStream get$utputStream* + =eturns the $utputStream associated with the invoking socket.
=ecent Java version has added the get(hannel* + method to Socket and this method returns a
channel connected to the Socket obGect.
2.+ ,CP$P "erver "ockets
The ServerSocket class is used to create servers that listen to either local or remote client
programs to connect to them on published ports. Since, the ;eb is driving most o! the activit% on
the "nternetL this section develops an operational web *:TT)+ server. ServerSockets are quite
di!!erent !rom normal Sockets. ;hen %ou create a ServerSocket, it will register itsel! with the
s%stem as having an interest in client connections. The constructors !or ServerSocket re!lect the
port number that %ou wish to accept connections on and optionall%, duration o! the queue !or said
port to be. The queue length tells the s%stem how man% number o! client connections can be le!t
pending be!ore it should simpl% re!use connections. The de!ault number client connection is 60.
The constructors might throw an "$@ception under adverse conditions. "n Table 1.6 the method
name o! server socket constructor is given
,ab#e 2./ "erver "ocket Constructor
1etho! Name %emarks
ServerSocket*int port+ (reates server socket on the speci!ied port with a queue
length o! 60.
ServerSocket*int port, int maxQueue+ (reates a server socket on the speci!ied port with a
maimum queue length o! maxQueue.
ServerSocket*int port, int maxQueue,
"netAddress localAddress+
(reates a server socket on the speci!ied port with a
maimum queue length o! maxQueue. $n a
multihomed host, localAddress speci!ies the ") address
to which this socket binds.
$n a multihomed host, localAddress speci!ies the ") address to which this socket binds.
ServerSocket has a method called accept * +, which is a blocking call that will wait !or a client to
initiate communications and then return with a normal Socket that is then used !or
communication with the client. The recent version o! Java added the get(hannel* + method to
ServerSocket and returns a channel connected to the ServerSocket obGect.
2.. 2niversa# %esource 3ocater )2%3*
The ;eb is a loose collection o! higher-level protocols and !ile !ormats and all o! them are
uni!ied in a web browser. $ne o! the most important aspects o! the ;eb is that it has devised a
scalable wa% to locate all o! the resources o! the "nternet. $nce %ou can reliabl% name an%thing
and ever%thing, it becomes a ver% power!ul paradigm. The ,ni!orm =esource <ocator *,=<+
does eactl% the same. The ,=< provides a reasonabl% intelligible !orm to uniquel% identi!% or
address in!ormation on the "nternet. ,=<s are ubiquitous, which means that ever% browser uses
them to identi!% in!ormation on the ;eb. "n !act, the ;eb is reall% Gust that same old "nternet
with all o! its resources addressed as ,=<s plus :T3<. ;ithin JavaCs network class librar%, the
,=< class provides a simple and concise A)" to access in!ormation across the "nternet using
,=<s.
Two eamples o! ,=<s are httpF##www.bdu.ac.in# and httpF##www.bdu.ac.inF90# inde.htm. A
,=< speci!ication is based on !our components. The !irst is the protocol to use, separated !rom
the rest o! the locator b% a colon *F+. (ommon protocols are http, !tp, gopher, and !ile, although
these da%s almost ever%thing is being done via :TT) *in !act, most browsers will proceed
correctl% i! %ou leave o!! the &httpF##' !rom %our ,=< speci!ication+. The second component is
the host name or ") address o! the host to useL this is delimited on the le!t b% double slashes *##+
and on the right b% a slash *#+ or optionall% a colon *F+. The third component, the port number, is
an optional parameter, delimited on the le!t !rom the host name b% a colon *F+ and on the right b%
a slash *#+. *"t de!aults to port 90, the prede!ined :TT) portL thus &F90' is redundant.+ The !ourth
part is the actual !ile path. 3ost :TT) servers will append a !ile named inde.html or inde.htm
to ,=<s that re!er directl% to a director% resource. Thus, httpF##www.bdu.ac.in # is the same as
httpF##www.bdu.ac.in #inde.htm. JavaCs ,=< class has several constructors and each can throw a
3al!ormed,=<@ception. $ne commonl% used !orm speci!ies the ,=< with a string that is
identical to the one displa%ed in a browser.
The !ormat o! the ,=< (onstructors are given below
,=<*String urlSpecifier+
The ,=< constructor !ormats given below allow %ou to break up the ,=< into its component
partsF
,=<*String protocolName, String hostName, int port, String path+
,=<*String protocolName, String hostName, String path+
Another !requentl% used constructor allows us to use an eisting ,=< as a re!erence contet and
then create a new ,=< !rom that contet. Although this sounds a little contorted, itCs reall% quite
eas% and use!ul.
,=<*,=< urlObj, String urlSpecifier+
"n the !ollowing eample, we create a ,=< to www.bdu.ac.in to download page and then
eamine its propertiesF
## -emonstrate ,=<.
import Gava.net.KL
class ,=<-emo M
public static void main*String argsIJ+ throws 3al!ormed,=<@ception M
,=< bdu,=< N new ,=<*OhttpF##www.bdu.ac.in#downloads O+L
S%stem.out.println*O)rotocolF O Q bdu,=<.get)rotocol*++L
S%stem.out.println*O)ortF O Q bdu,=<get)ort*++L
S%stem.out.println*O:ostF O Q bdu,=<.get:ost*++L
S%stem.out.println*O4ileF O Q bdu,=<.get4ile*++L
S%stem.out.println*O@tFO Q bdu,=<.to@ternal4orm*++L
R
R
;hen %ou run this, %ou will get the !ollowing outputF
)rotocolF http
)ortF -/
:ostF www.bdu.ac.in
4ileF #downloads
@tFhttpF##www.bdu.ac.in #downloads
Notice that the port is S/L this means that one was not eplicitl% set. Now that we have created a
,=< obGect, we want to retrieve the data associated with it. To access the actual bits or content
in!ormation o! a ,=<, %ou create a ,=<(onnection obGect !rom it, using its open(onnection*+
method as given below
url.open(onnection*+ and open(onnection* + has the !orm o! ,=<(onnection open(onnection* +
and it returns an ,=<(onnection obGect associated with the invoking ,=< obGect. "t ma% throw
an "$@ception.
2./ 2%3Connection
,=<(onnection is a general-purpose class !or accessing the attributes o! a remote resource. $nce
%ou make a connection to a remote server, %ou can use ,=<(onnection to inspect the properties
o! the remote obGect be!ore actuall% transporting it locall%. These attributes are eposed b% the
:TT) protocol speci!ication and as such onl% make sense !or ,=< obGects that are using the
:TT) protocol. "n the !ollowing eample, we create a ,=<(onnection using the
open(onnection* + method o! a ,=< obGect and then use it to eamine the documentCs properties
and content.
## -emonstrate ,=<(onnection.
import Gava.net.KL
import Gava.io.KL
import Gava.util.-ateL
class ,(-emo
M
public static void main*String argsIJ+ throws @ception M
int m%(har"ntL
,=< m%,=< N new ,=<*OhttpF##www.internic.netO+L
,=<(onnection m%(on N m%,=<.open(onnection*+L
## get date
long d N m%(on.get-ate*+L
i!*dNN0+
S%stem.out.println*ONo date in!ormation.O+L
else
S%stem.out.println*O-ateF O Q new -ate*d++L
## get content t%pe
S%stem.out.println*O(ontent-T%peF O Q m%(on.get(ontentT%pe*++L
## get epiration date
d N m%(on.get@piration*+L
i!*dNN0+ <".=A=H
S%stem.out.println*ONo epiration in!ormation.O+L
else
S%stem.out.println*O@piresF O Q new -ate*d++L
## get last-modi!ied date
d N m%(on.get<ast3odi!ied*+L
i!*dNN0+
S%stem.out.println*ONo last-modi!ied in!ormation.O+L
else
S%stem.out.println*O<ast-3odi!iedF O Q new -ate*d++L
## get content length
int m%len N m%(on.get(ontent<ength*+L
i!*m%len NN -/+
S%stem.out.println*O(ontent length unavailable.O+L
else
S%stem.out.println*O(ontent-<engthF O Q len+L
i!*m%len TN 0+ M
S%stem.out.println*ONNN (ontent NNNO+L
"nputStream input N m%(on.get"nputStream*+L
int i N m%lenL
while ***m%(har"nt N input.read*++ TN -/++ M ## UU *--i V 0++
M
S%stem.out.print**char+ m%(har"nt +L
R
input.close*+L
R else
M
S%stem.out.println*ONo content available.O+L
R
R
R
The program establishes an :TT) connection to www.internic.net over port 90. ;e then list out
the header values and retrieve the content. :ere are the !irst lines o! the output *the precise output
will var% over time+.
-ateF ;eb Jul% /6 /1F/7F51 (-T 1008
(ontent-T%peF tet#html
No epiration in!ormation.
<ast-3odi!iedF ;ed Jul% /6 /7F61F21 (ST 1008
(ontent-<engthF 6188
NNN (ontent NNN
PhtmlV
PheadV
PtitleV"nterN"( W The "nternetXs Network "n!ormation (enterP#titleV
Pmeta nameNOke%wordsO contentNOinternic,network in!ormation, domain registrationOV
Pst%le t%peNOtet#cssOV
PT--
p, li, td, ul M !ont-!amil%F Arial, :elvetica, sans-seri!R
--V
P#st%leV
P#headV
The ,=< and ,=<(onnection classes are good enough !or simple programs that want to connect
to :TT) servers to !etch content. 4or more comple applications, %ouCll probabl% !ind that %ou
are better o!! stud%ing the speci!ication o! the :TT) protocol and implementing %our own
wrappers.
2.4 (atagrams
4or most o! %our internetworking needs, %ou will be happ% with T()#")-st%le networking. "t
provides a serialiBed, predictable and reliable stream o! packet data. This is not without its cost,
however. T() includes man% complicated algorithms !or dealing with congestion control on
crowded networks as well as pessimistic epectations about packet loss. This leads to a somewhat
ine!!icient wa% to transport data. The -atagrams provide an alternative approach !or transporting
data !rom the source to destination. The -atagrams are bundles o! in!ormation passed between
machines. $nce the datagram has been released to its intended target, there is no assurance that it
will arrive or even that someone will be there to catch it. Similarl%, when the datagram is
received, there is no assurance that either it has not been damaged in transit or that whoever sent
it is still there to receive a response. Java implements datagrams on top o! the ,-) protocol b%
using two classesF The -atagram)acket obGect is the data container, while the -atagramSocket is
the mechanism used to send or receive the -atagram)ackets.
2.4.1 (atagramPacket
-atagram)acket de!ines several constructors and are given below. The !irst constructor speci!ies
a bu!!er that will receive data and the siBe o! a packet. "t is used !or receiving data over a
-atagramSocket. The second !orm allows %ou to speci!% an o!!set into the bu!!er at which data
will be stored. The third !orm speci!ies a target address and port, which are used b% a
-atagramSocket to determine where the data in the packet will be sent. The !ourth !orm transmits
packets beginning at the speci!ied o!!set into the data. Think o! the !irst two !orms as building an
&in bo' and the second two !orms as stu!!ing and addressing an envelope.
-atagram)acket*b%te dataI J, int size+
-atagram)acket*b%te dataI J, int offset, int size+
-atagram)acket*b%te dataI J, int size, "netAddress ipAddress, int port+
-atagram)acket*b%te dataI J, int offset, int size, "netAddress ipAddress, int port+
There are several methods !or accessing the internal state o! a -atagram)acket. The% give
complete access to the destination address and port number o! a packet as well as the raw data
and its length. :ere are some o! the most commonl% usedF
,ab#e 2.4 (atagramPacket access metho!s
1etho! Name %emarks
"netAddress getAddress* + =eturns the destination "netAddress, t%picall% used !or sending.
int get)ort* + =eturns the port number
b%teI J get-ata* + =eturns the b%te arra% o! data contained in the datagram. 3ostl%
used to retrieve data !rom the datagram a!ter it has been received.
int get<ength* + =eturns the length o! the valid data contained in the b%te arra%
that would be returned !rom the get-ata* + method. This t%picall%
does not equal the length o! the whole b%te arra%.
(atagram "erver an! C#ient
The !ollowing eample implements a ver% simple networked communication client and server.
The 3essages are t%ped into the window at the server and written across the network to the client
side and displa%ed.
## -emonstrate -atagrams.
import Gava.net.KL
class ;riteServer M
public static int server)ort N 889L
public static int client)ort N 888L
public static int bu!!erYsiBe N /012L
public static -atagramSocket dsL
public static b%te bu!!erIJ N new b%teIbu!!erYsiBeJL
public static void TheServer*+ throws @ception M
int posN0L
while *true+ M
int c N S%stem.in.read*+L
switch *c+ M
case -/F
S%stem.out.println*OServer Zuits.O+L
returnL
case X>rXF
breakL
case X>nXF
ds.send*new -atagram)acket*bu!!er,pos,
"netAddress.get<ocal:ost*+,client)ort++L
posN0L
breakL
de!aultF
bu!!erIposQQJ N *b%te+ cL
R
R
R
public static void The(lient*+ throws @ception
M
while*true
M
-atagram)acket p N new -atagram)acket*bu!!er, bu!!er.length+L
ds.receive*p+L
S%stem.out.println*new String*p.get-ata*+, 0, p.get<ength*+++L
R
R
public static void main*String argsIJ+ throws @ception M
i!*args.length NN /+
M
ds N new -atagramSocket*server)ort+L
TheServer*+L
R
else
M <".=A=H
ds N new -atagramSocket*client)ort+L
The(lient*+L
R
R
R
The above sample program is restricted b% the -atagramSocket constructor to run between two
ports on the local machine. To use the program, run Gava ;riteServer in one window as client.
Then run Gava ;riteServer / and this will be the server. An%thing, which is t%ped in the server
window will be sent to the client window a!ter a newline is received.
2.5. C#ient$ "erver app#ication using JAVA %1
=emote 3ethod "nvocation *=3"+ allows applications to call obGect methods located
remotel%, sharing resources and processing load across s%stems. The other s%stems !or
remote eecution, which require onl% simple data t%pes or de!ined structures, be passed
to and !rom methods. :owever, =3" allows an% Java obGect t%pe to be used even i! the
client or server has never encountered it be!ore. =3" allows both client and server to
d%namicall% load new obGect t%pes as required. =3" !acilitates obGect !unction calls
between Java Virtual 3achines *JV3s+. JV3s can be located on separate computers %et
one JV3 can invoke methods belonging to an obGect stored in another JV3. 3ethods can
even pass obGects that a !oreign virtual machine has never encountered be!ore allowing
d%namic loading o! new classes as required.
"n the programmer perspective, the =3" application comprises o! the two separate programs and
called server and client. The server program creates some remote obGects, makes re!erences to
these obGects accessible and waits !or clients to invoke methods on these obGects. The =3"
application provides the mechanism b% which the server and the client communicate and pass
in!ormation back and !orth. The =3" distributed application uses the =3" =egistr% to obtain a
re!erence to a remote obGect. The server calls the registr% to associate a name with a remote
obGect. The client looks up the remote obGect b% its name in the serverCs registr% and then invokes
a method on it.
2.5.1 Program !escription
"n this section, we write a simple eample program to send massage !rom =mi(lient to the
=miServer. ;e create'=eceive3essage"nter!aceO inter!ace and the inter!ace de!ine the methods
that can be invoked !rom the client. @ssentiall%, the inter!ace de!ines the clientXs view o! the
remote obGect and we will create a class named O=3"ServerO. The =3" Server accepts tasks !rom
clients, runs the tasks and returns an% result. The server code consists o! an inter!ace and a class.
The class &receive3essage*+' method, which is called !rom the remote client. This class is the
implementation o! the =3" inter!ace. The =miServer creates the &registr%' and is the same as a
director%. This obGect is looked up !rom a remote program b% the name. This registr% is accessed
!rom a remote obGect either b% the ") address or host name and the port number. "n server
program, create=egistr% *+ is the method, which creates and eports a registr% on the local host
that accepts requests on the speci!ied port.
%eceive1essagenter-ace.java
import Gava.rmi.KL
public inter!ace =eceive3essage"nter!ace etends =emoteM
void receive3essage*String + throws =emote@ceptionL
R
The above code de!ines the =3" inter!ace. The receive3essage*+ method is implemented in the
server class.
the code o! =3" Server is given below
import Gava.rmi.KL
import Gava.rmi.registr%.KL
import Gava.rmi.server.KL
import Gava.net.KL
public class =miServer etends
Gava.rmi.server.,nicast=emote$bGect implements =eceive3essage"nter!aceM
String addressL
=egistr% registr%L
public void receive3essage*String + throws =emote@ceptionM
S%stem.out.println*+L
R

public =miServer*+ throws =emote@ceptionM
tr% M
address N *"netAddress.get<ocal:ost*++.toString*+L
R
catch*@ception e+M
S%stem.out.println*OcanXt get inet address.O+L
R
int portN5151L
S%stem.out.println*Othis addressNO Q address Q O,portNO Q port+L
tr%M
registr% N <ocate=egistr%.create=egistr%*port+L
registr%.rebind*OrmiServerO, this+L
R
catch*=emote@ception e+M
S%stem.out.println*Oremote eceptionOQ e+L
R
R
static public void main*String argsIJ+M
tr%M
=miServer server N new =miServer*+L
R
catch *@ception e+M
e.printStackTrace*+L
S%stem.eit*/+L
R
R
R
The above class uses <ocate=egistr% class to create a remote obGect registr% that accepts calls on
a speci!ic port.
,he co!e o- %1 C#ient is given be#ow
import Gava.rmi.KL
import Gava.rmi.registr%.KL
import Gava.net.KL
public class =mi(lientM
static public void main*String argsIJ+M
=eceive3essage"nter!ace rmiServerL
=egistr% registr%L
String serverAddressNargsI0JL
String server)ortNargsI/JL
String tetNargsI1JL
S%stem.out.println *Osending O Q tet Q O to O QserverAddress Q OFO Q server)ort+L
tr%M
registr%N<ocate=egistr%.get=egistr% *serverAddress,*new "nteger*server)ort++.intValue*++L
rmiServerN*=eceive3essage"nter!ace+*registr%.lookup*OrmiServerO++L
## call the remote method
rmiServer.receive3essage*tet+L
R
catch*=emote@ception e+M
e.printStackTrace*+L
R
catch*Not.ound@ception e+M
S%stem.err.println*e+L
R
R
R
"n the above program, lookup*+ is the method, which returns a re!erence, a stub, !or the remote
obGect associated with the speci!ied name. "! the =3" client sends an% t%pe o! message then
message will be displa%ed on the =3" Server.
6&ercise
/. -evelop a chat server using client server concept, which connects two or more clients so
that the input o! one client is output to all other clients.
1. -evelop and window based :TT) client to connect to the :TT) server. Also,
incorporate mechanisms to understand the :T3< and displa% the output in %our client.

You might also like