0% found this document useful (0 votes)
76 views

Network Programming-Min

TCP and UDP are common network protocols used in Java programming. [1] TCP provides reliable transmission of data between computers using a connection-based protocol that guarantees delivery. [2] UDP transmits data as independent packets without establishing connections, making it faster but without guarantees about delivery order or receipt. [3] Network programming in Java uses classes in the java.net package that allow communication over TCP and UDP without dealing directly with low-level network details.

Uploaded by

Manish Aryal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Network Programming-Min

TCP and UDP are common network protocols used in Java programming. [1] TCP provides reliable transmission of data between computers using a connection-based protocol that guarantees delivery. [2] UDP transmits data as independent packets without establishing connections, making it faster but without guarantees about delivery order or receipt. [3] Network programming in Java uses classes in the java.net package that allow communication over TCP and UDP without dealing directly with low-level network details.

Uploaded by

Manish Aryal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

. . . .

NET\VoRK Pao
· · ··.' · · : . .. . · .·.
0
RAMMINc

Chapter Outlines

· study of this chapter, you will be able to:


t comprehensive
,,. ounderstand
_ the concept of socket in network programming
•10 exp}am .
• the difference between TCP and UDP protocol in network programmin& ,
io de . ,
UOp lllonstrate the steps involved in creaimg netw0rk program• usmg TCP an

~~u .
to CJcplo RL and related classes in socket progranunt"ll .
. - . d demonstrate it
re different APls used in Java mail_an
Pn.1~r111t11t1ill$ CS .....
ffl Adv""c,'<lJ.v• ' G JIAII

tlNO -
rnv-~ that execute across multiple d.,.,_
"-11
8J NIU~ other using a n~twork. It ;, ai.,
'ting programs
Th k
rogramm1·ng refers to wri
II conn ected to each . p rograo,3
cep t o f socke t to write II that
( e term networ
. p d
hkh the e vices are a we us e the conf the J2SE APis conta ins· a co ection of
computers), mketw
progra mming t,ecause 'd us to Write
. t'JOn deta ils, allowing
Th ·ava ne t package oun1ca
. te in
referred as soc . th e network. eh J low- • level comm . va net package prov1 es support for
can rommuruca
classes and interfck.--es that provide UDP. The
I ,·ng the problem a t hand.
t e These · tocols lie at transport laye, of
Ja pro
focus on so ' l TCP &
programs that ~twork protocols:
the hrn common
TCP/ IP protocol suit
'

, Application
(}flTP, ftpI telnet, ....)
-

' Transport
(TCP, UDP, ....)
~

Network
(IP, ....)

Link
(device driver, ....)

. Fig 1.1 TCP/I~ protocol stack.


- .

· unicate over the network, w e do programming at the


"'hen we write Java programs 'th the TCP and UDP layers. Instead,
'
that
eed t0 comm
concern ourseIves w1
•pplication layer. We don t n _ ka These classes provide system-independent
we can use the CW6eS
network commuruca on. in the J3Va.net
' pac ge. ams should use,"'
. ti' However to decide which Java classes your progr
need to understand how TCP and UDP differ.
hdata
s.1.1 Transmission Control Protocol (TCP)
lbtination
TcP /Transn,;,.;on Control Protocol/ is a COnnection-based protocoJ t prov, es .:h
tha .d a reliable
now of data between two computers, When two applications want to communicate to e_
other reliably, they establish a connection and send data back and forth over that conn .
ectJOI\.
This is analogous to making a lelephone call. ll Ra111 (l<almandu) want to speak to HaJi
(Pokharaj, a connection is established when Ram dials his phone number and Harl answer,.
l
Ram and Har; send data back and forth over the COllnection by speaking to one another ""'
f the phone lines. Like the phone ro111pany, TCP IIUarantees that data sent from one end of to!
is reported. •ctuaUy gets to the other end and in the same order it was sent. Otherwise, an en<'
connection

The Hypertext Transfer Protocol (lilTpJ, File Transfer


. Protocol
. (FI'P) .Telnet etc are exainP~. .

of li · '
channel. The order in which the d•ta !S
and<alions
seot•Pp that
rece1vecf require
over k · conununicalion
th atwreliable · • al
• ne or IS critic to the sucee.. of these applications.
. .• • ,, 1;zr~q ~,, , .,
~ -- - ~; (-i
.. . I r ' , lr.€'[11-',.., .!~.;1:>;r,

~ ~.f:,,1,;•ir~·~d:-•,.
user Datagram Protoco1 Nctw
orkini Pr°'U
1PI, (lJ~~I Datagram Protocol) ;8 a Protac(lJl)p) 5
'"'ming () o,,Pk ,
uO s from one computer to I :r /Si 221
o that 84! d .
,ra111 ' .k TC another , n s ltld
,1,,1i1s tion-based h e P. Rather, it send . With no gu e,>endent Packets
i,,11J1l" 1·cation to another. Sending dat s independ<!nt araniees about a . of data, (ailed
apP t • order f d . .
,,,,~. , The o eh very is not imagran,s is. Packets f
much like rr1vaJ UOp .
?data, called is not i1a
,f\11ct!, t f any other But Portant and . Bending a letter hr gram,, from
i it:nden o
C, ,n1u . h .
. ' cornrnunicar

' I cl1annel is t e pmg comrnand Th


rnp e of a se .
ts not guar
jo,l0l'f nication provided by TCP, Exa I ton done by USe anteed, and each the !al
of UOp pr
rvice that d
t ough

ge 1S
otocoJ is faster Iha
rn: .
pb e • ep <>esn'
I\',. unication between two programs over th urpose of the ping t need the guarantee of n a
ct101n1 e network, command is to test the
8,1,3 Unde~nding IP Address and Port
rally speaking, a computer has a single h .
Gell€
tined for a particuIar computer arrives through P ys1cal
ha connecti . on to the network. All data
d• ded for different applications running on th 1 1
COnnection. l!owever, the data may be
iJltenhich application to forward the data? This isedcompuhrter. So how does the computer know
to w
say that "Port is a number that is used to identify
· one t ough the use of
application within acomputer" ports. Thus we can
Dla transmitted over the Internet is accornpanied by address· inf .
a , , . mg ormation
(.'Omputer a~d the _port for which 1t 1s destin~. The computer is identifiedthat identifies the
by its .bit IP
address, which IP (internet protocol) uses to deliver data to the right computer on the network.
32
Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right
application. In connection-based communication such as TCP, a server application binds a
socket to a specific port number. This has the effect of registering the server with the system to
receive all data destined for that port. No two applications can be bound to the same port.
p
unming at t!'f
server 0
lyers. Instead r TCP
1-indepenoou client
hould use, wi fig. 8.2: Poff .
.
In datagram-based communication such as UDP, ~ dataS::on. as illustrated in this figure:
contains the port number ci its
destination and UDP routes the packet to the appropnate a_PP_-..

1:,~
[des a ffJJII
[licate to ~
at conn~
-" to f l"
;peill' eJS
. ar,,Vi Datagram
Bat1
the!
eano dJ~
01'6

·. --- Data
I0at1J
pne en ~ · ·· , . - ·· · unication. berS The p0rt
,al' . . F'gure 8.3: Port and coJDJII presented by 16-bit ::'knO~ services
t
1~~
e-#.f
care oil''
Port •
n'lllnbers range from Oto 65,535 1,ecause Po rts are re
. ted· they are reserved
l\litnhers ranging from O-1023 are restric se~ices. These
S\ich as lfrrp and FrP and other system them-
app1, b. d to
llCations should not attempt to lil
parts are
use by w
for ed well-knOWTI ports. Our
call
,,, •••••
_ _ , ..
~,F.
,,i .. , 6.
·
't , • r 111111t1ll~'l. _ -nflllf
·1 cATION ., t of,,,e-,,,, I
f30 A1h·,111~'l.'d.fllVII l \,-.:. ~
AND soc,t£••
,. ~ l,r.,d
~
COl'IJn-•__:,
the transport layer. Net,,..,
. ~ ,oC'"
t~t
""i9 ~ .
:I

U SoCJtETS networks at . g file J/0. In fact, socket ha ot~ 'P" ~(!e


. (nr prt'~ramn1ing ,liar to perfo~rJllO de endent of a progra l\~Ie r'° ~rt
Sod.et i!'I an in~'r:1~:-kets is vt•ry n,uch si :munication is in rJl ~ritten in Java langu:llg tl'e r
t"'\"lmmunkation usini,, . ' S..'ll·kt't-ba~d co1 socket progra o am. ~ _,etl
is treat<-d m.e file hilndll- •. it That means, a or c++) socket pr gr ur
JanM1ace u~ for impk111c11t1'.'i\ ··n non-Java (soy C ket that is bound to a specific nr.... } ,,o""eJ
•-c,- c-
rommunkare t-t, a prn~ran
'wnth:n t d h s a soc
.,. co111puter an a
a c:pt'l'.1 ic
f
ction request. I everyt mg goes Weij
h'
k t ho
rv,1, 7
pr.: flt,
~
i
und to a'
k a conne
A ~n-er pn,gram nins o11 . ,. a client to ma e
The sen•er listt-ns to t ,e • i socket
h connection.
''")r
. Upon accep a ' t nee t
h server gets a new soc e
e
t port num
·t
ber so that 1 can con ue to list
.
tin'
en
tf'he
p· .al'.
fitj
the ~n-er <h"---erts t e ·k t and a differen . the connected chent. .~ ~-,
. 1t flt:'\:~ ..• a new soc e hile serving v•- !
different. I''rt-
·nal .,,.,.-ket (cir connec·ti·on requests w ..,.---····•.. --~-~
. ---
. --~-....-----.~--•·--"".... ."'7•~,,.....,, i . Je~.i_fl
~P.
J
the
to onp .,._ . Aa -~ . . . . . _.--JN-TJiB JDK ,..i rs:11. j
~ -NnwoaKJMO ' - ~ - ·
. t over the Internet. Some of the cl~
to commUIUca e
oiJtSJ•.
TCP or UDP
Ja,·a rrograms can use
fll'O\ided in ;a,•a.net package are.
.
d
. ..
· te sockets when we use TCP for ~ \
• Sockn Class: The Java Socket class is use to crea
rommunication.
k t
.. .

fs used to crea e soc


.

·· ·t kets fo·r servers wh


en I
..
~-
01
Cl08
• Server Socket Class: The ServerSoc e ~1a 55 · · · - ·· · tns • ~
rcJ> is used for communication. _. . .. •· . · · · .

• J.nA.ddrrss Class: The InetAdd


ress is Java's representation of an IP address. Instances outj 1

of this class are used together with UDP D~tagr~kets and TCP Qnce
Sockets and ServerSockets. . .
stre
• DatagramSoclcet Class: This class is used to create sockets at client or server when we
use UDP protocol for communication i~
• DatllgramPaclcet Class: This class is used to create datagram packets that are
exchanged between UDP clients and UDP servers. • Well
• URL Class: The Java URL class represents an URL. URL is an acronym for Uniform 8.4.2 Sb
Resource Locator. It points to a resource on the World Wide Web.
t Crea
• URLConntction Class: The Java URLConnection class represents a communication link
between the URL and the application. This class can be used to read and write data to Ser,

1.4 ·-....... . ----


the specified resource referred by the URL.

-"7J t
The two key classes from the J·ava.net ka .
are: pac ge used m creation of server and client programs
Socket
ServerSocket
' ··•"Ii'•-
~- ~ ·
. -
·,~ ;--
·t· Network"
,. J StePS for wr1 1ng Client P rogran, tn& PrO&r .
"' . 1·"'
orett~et
a ocket.
8
arnmin& o ----
Chapter ii 231

t, ~~~ ~ client= new Socket(


SO(: soc server add
Pto~tha.. ~ . staternent creates a socket f
flllS . -
or chent ress, Port i.
- d) •
a lc\r) , ~ vide IP address or domain nam computer Wh· '
&llil~~"
pro be . hi e of the co . ile creatin
~~~ .i.e p0rt num r m w ch server liste mputer wher g socket we need to
µ• ns to the cl. e server pro
a Sl>ec /"Inell an input stream and output tr tent. gram executes and
hin ific vr- 8
eam to th
ket ~Oes~
i sconner . ins=new Scanner( cl i.ent e socket
.getinputstre
n1-;- ll.r\q , rintwri ter outs= new Pri.ntWri. t er(client . am());
~•uet()~ P
'fhe {irst statement gets input stream f . • getoutputstream() true) .
o c1ient's sock , '
the second statement gets output stream of di t' et and opens Scanner on it. Simil 1
f~~ . - en s socket and o . . . ar y,
ii?:: gead from and ~te to the sockets stream pens PnntWnter on it.
3,
rs=ins.next~ine();
outs.println( s);
:l'cPfor The first statement reads a line from client' 5 socket · and puts it in variabl
· ' ' d the
second
__ statement
. - write
-- the value
. of string variabl , , . .
e ss mto client's socket. e rs an
~rversWhen
4.
oose the streams .- . . .
ins.close();.
ess. Instances outs. ciose(); -
Once 1/0 is completed, above statements are used to close input stream and output
stream of client's socket.
-
rerwhenwe 5. Oose the socket. . :
dient.closeO
are We use this stat~me~t to ~lose.the ~onnection between client and server computers.
~ • :-- ~- .~·• • - -!.!' ~ . , . .... , •

uniform 8.4.2 Steps for writing Server program


t Create the Object of ServerSocket clasS
2345
unication link ServerSocket server= new. serversocket(d th );gument represents the port number
vnte data to This statement create socket for the server an e ar . . .
to which the server listens. · .·
t Accept the connection front the client · .- , ·· -
Socket client~ser~~r.acc.ept(); · d ·tsfortheclientconnection
infinite loop an wai ·· ·
After creating the socket it enterS into the . _
by using accept method. ·
3. Get · . of the socket . . ·. -.
input and output streaJDS tstream()); ..
S ( ver. getinpu .
canner ins = new scanner se,: _ ·· · ·
utstream (), true) i
etoutP .
·.. a erver. g d pens Scanner on it. Simi!
raf11t1'1'''(' er(S tan o . W. arly
ced Java f'r\.~ intwri t r' soC)(e d opens Pnnt nter on it ,
AJvsn . w pr r:e s oeket an .
%32 ts" ne of se (s s
printWriter ou ·npot streaf11 ..., of sef'le
t gets I 5treaw .
The first stater11en m>ts ootpot
terl'ler,t i, -
the secor,d sta SO'l(et
. Data to the
Read/W"tt . (). ts it in variable 'rs' and 11._
. xtL ine ' r's 5oek et and pu
ers's socket. "'
rs==ins.ne
outs.printLn(ss)i 1·ne fro!ll ser:e ·able 'ss' mto set"
ads a , ·ng var1
t.:...,t staten,ent re 1ue of str•
The '"" ·te the va
second statement wrt
oose strtatn•
s. used to close input stream and output
ins.close()i
outs closeOi taternents are -
. 1 t d above s
()nee I/O is cornP e e '
stre,arn of. client's socket.

6.
ooseSocket
server.close() .
client. close() -· ection between client and server computers.
J.....,.. statements to close the conn .
weuseu-=-- '
ExaJDple
// client program.
illJ)01°t java.net.•;
import java.io.•;
import java.util.*;
public class HsgClient
{
public static void main(String argsU) ~h~~ws _I~E~c~~ti~~
{ " ." ' ,' ' , - . .. . ..

/ / Open your connection to a server, at port 1254


socket cs• new Socket("localhost",1254);

/ I Get an input file handle from the socket and read the input
Scanner ins= new Scanner(cs.getinputStream()); .
PrintWriter outs= new PrintWriter{cs.getOutputStr~am(), true);

//Perform IO
outs.println("Hello Server");
st rings= ins.nextline(); ·•~ · }

System. out. println ("From Server: "+s );


// ,1ose streams and connect ·
j.nS. close() ;
lon
outs. close();
cs. close();

riable,
ket, ts' ~Q \

ver program.
I1ser
. rt java. net.*;
)."'° rt . *;
java. 10.
illPort java. ut1• 1 . *;
1-i>O

c1ass MsgServer .

public static void. main(String arg [])


{ - : . -- ·. _ s · throws !OE xception
.

II Regi~ter service o~· port 12s4


er COIIl.puters,
.ServerSoc ket ,s s = ~ew·. serv~rSocket
. (1254);

II .Wai~ a~d :accept_a ·c~nnection


Socket cs=ss·.accep~{);

I I Get_·a communic~tion •·stream associated with the socket


. .
Scanner ins=new Scanner( cs. getinputStream());
PrintWriter outs= new PrintWriter(cs.getOutputStrea11(), true);

I I Perform I/0
Strings= ins.nextline();
System.out.println("From Client:"+s);
outs.println("Hello Client") ;

input
// Close streams and connection
outs . close ();
true); .
ins• close();
cs.close();
ss •close();
}
, n 1111111i1~
234 Acivillll'-'"• .111V'l• l'l\)~

Out:rut
-- - 311cmd.e>~
ii C:\Windo,oi\srS~

I
l g1eehat ~
//Sift iaVa.net,
ti)rt, ·o •;
!Dlr- iava.1 ·
;ava.util -
..,.rl,...
~Y"·- J
ia,pOrlSjngleCha
~

I public static
-
I -
5erVe

:1
~g,
PrintW1
Scannei
Example Single Chat Application
I I Single Chat client program.
import java.net.*; { .1
import java.io.*;
Sys
·
import iava.u til.•;
public class SingleChatCJient
smJ
{ out
nn
public static void main(String args□) throws IOException .
( Sy!
}While(
Socket cs= new Socket("localhost",1254);
0 uts.clc
Scanner ins= new Scanner(cs.getlnputStreamQ); ~-cl()!
CS,cl094
PrintWriter outs= new PrintWriler(cs.get0u1put5treamO, true);
Scanner ink=new Scanner(Systern.in); l SS,cl094
I
string rmsg, smsg;
do
(
rmsg=ins.nextLineO;
System.out. println("\
.
Sys tem.out•Pnnt("q· tServo...,, -
+l'llts )
'-l;
. tent·")· g;
smsg = ink.nextLineQ• · '
outs.println(smsg); '
}while(rmsg.equals("buy")'==
ms.closeQ; - · true)·'
outs.closeQ;
cs.closeQ; ·

l -
// Single Chat Server Proiam. __
import java.net.*; ~ _
import java.io.*; · ·_c: _ _-_
import java.util.*; ~ - -~ __
~SingleChatServer -~> ·:-.< __
I
pub~c s~tic void ~(String argsfo furows ioEx - tion
r- _,_-_:._.:, --_- .: -- -: -;_- -~- - --_- ---.
cep
· . ~e6>eket ss = new·Setvefuket(l~); · -·
Socket cs=ss.acceptQ; ·; -:'. ·• · · : - ·.,.-_:
~ ini~w Sc~er-(cs.getlnputStreamO);
PrintWriJe;outs~ ne~ PrintWriter(cs.getOutputStreamO, true);
Scanner ink=new Scanner(System.in); ·
String rmsg, smsg; '-=~--
do
{
System.out. print("Server:");
smsg = ink.nextLineQ;
outs.println(smsg);
nnsg=ins.nextLineO; g)·
·
System.out.println ("\tClient:"+nns
· '
}while(rmsg.equals("buy")!=trUe);
0 uts.closeQ;

ins.cioseQ;
cs.cioseQ;
SS.clOSeQ;
I }
u 1o r u 111111 i 11 ~
236 Ad vanced Juwi r l'C , ~

Outp ut
--- --- - 7 , , lul
i
·1
fl: ,,J,w,, ,,j"v" S inglcC hatSo rvor
Sc1•vP r: lu~ 1 lo
Clien t.:hi
!;rrvt_• r: ]( b?
Clien t•~c fine •••.•. • n ul
S~rvt~r :a;1e <l.l!:O fine
Clien t a,Ju,t Aht .1,,v11 C )ll!lllO~ "i
't•rt•f•t •: huy
Clien t :buy

o:,Jav a)jav a Single ChatC ]iftnt


Serve r:hell o
.]ient :hi
Server :)< 6 7
,: 1 i ent: ne fine .... : .. n ll?
. .
l 1t'nt
Server :ri1e a.l!;o fine
:uha.t aht jt'\Vcl. C la~:-:t:: :r?
string s
. . Serv,- r:buy
J 1rnt :huy system . a
When th
retrieV e t
displays

I
;,
&s .SocDT.PRooRAMMINci'USING UDP , socket.
., This stat
The UDP protocol provides a mode of network communica
tion w hereb y applications send client a
packets of data, called datagram's, to one another. Java
supp orts datag ram communication
through the following classes: · l5,2Steps
DatagramPacket
l
DatagramSocket Cet a eta
.
There is no concept of connection in the UDP system. Henc Datag
e tran~·m issio n of data onto the
network does not require any host to be listening. This
Para
8.5. 1 Steps of writing client Program t
1.
lee
Get a datagram socke t
byte(
DatagramSocket sock et D,,t,z
= new DatagramSocket(port) ;
This creates a socket for client without if .
port num ber. The serve r ge the part
5 ts
number from the DatagramPackets and peed ymg .
. sen 8 its respo nse to that port

~
O I .

'
ilii!.
i

:.

l'. nd request
.:,C Nc1Work ·
lt) o p
DatagramPack et pac ket = " roir•1
•l'l11t1ing o
new Dat Chapt er 81
1net add r, por t) soc ket. send ( agra mPacket(b 231
~ statemen t crea tes a dat Pac ket ) • Yte[]
Th... ' ' length,
agra
kngth of data in bytes, InctAd ~ rn Packet to
. , be
this 1s the requ est to serv er. Tl c,rcss, anct Port sent by s . .
. nun,b Pec1fy1ng ern pty b
le second t
n.-cciving Hus packe t, se rver Will er. Enipty yte array
s ateni en t send 6yte array indica t h'
packet. send alt s the pack es t at
messages to the et to the server. After
Get response port nu rnber s 'f•
peci 1ed in the
pac ket= new DatagramPacket(buf
soc ket. rece ive( pac ket) ; , buf , length)
;
The client creates a "receive" packet d
.
receive the reply from the server. Thean uses the Data
. . gramSocket receive method to
destined for the clien t comes through thereceikve method waits
. .
until a datagram packet
.
doesn't wait forever for a reply. soc et. Normally a I'
. .
' c ient sets a timer so that it
4. Display response
Stri ng s = new Stri ng(p ack et.g etD ata(
)) ;
Sys tem .out .pri ntln ("Fr om Server:" + s);
When the client receives a reply from the serve
r, the client uses the getData method to
retrieve that data from the packet. The clien
t then converts the data to a string and
displays it.
5, Close Socket
sock et. clo se( );
This statement closes the. data
.
gram socket that is. created for communication between
;vapplications ~~ client and server.
ll
·am commUJll·cabl)II 8,5,2 Steps of writing Server Program
1.
Get a datagra~ socket
)
DatagramSocket socket = new DatagrmnSocket(port;
mber specified in parame ter. This
· to I~ This instantiates Datagra mSocket with the port nu
,nof data on . h the server receive UD p packets·
. parameter is the UDP port from whic
2.
Receive request
byte[] bu/= new byte[256]; . . · k t(buf, buflengl/1);
DatagramPacke DatagramPac e
t packet = new
t create a datagram
SOcket.receive(packet); econd statemen t receives the
r 'M..
b te array and s_ Uy third statemen
ne first statement simply ereates a t by
1
Y . and ftlla
etS t1td client
,rver g Packet for receiving the pa cket sen
datagram packet.
238 Advanced Java Proo,orammif\$
3. Send response UDP Client");
· ("He/lo .... .
String s = new String }
buf = 5.gctBytes(); if, buif.length, address' port),
mPacket(bu ,
packet= new Datagra . Third statement instantiates
· f sendmg.
socket.se11d(packet); . repares data or d in above step and finally third
. d second statement p th data prepare
The first an b including e
DatagramPacket class : t to the client.
statement sends the pac e
4. Close Socket • .
·
socket.close(); _ ket that is created for communication between pub
h
This statement closes t e datagram soc
client and server. {
Example .
// UDPClient.java: A client program.
·
import Java.n et ••·,
import java.io.*; .
public class UDPClient
{
public static Void main(String args[]) throws IOException
{
/ /C reate Socket oatagralP
oatagramSocket socket= new DatagramSocket();

// send request
byte [] buf = new byte [ 256] ; ·:
InetAddress address = InetAddress. getByName ( "localhost •);
DatagramPacket packet= new DatagramPacket(buf, buf.length, address, 4445) ;
socket.send(packet);

// get response
packet • new DatagramPacket(buf, buf . length) ;
socket.receive{pa~ket);

// display response
String received ~
new st ring(packet. getData()) ;
System.out N~
· Printl n("
Work·lllg Pro
Quote &rani ... ,
Oft .,, "&O .
//close the he ·"'"""ent,
A- Cha ~
Pier s, 239
socket ' ...
ij

socket. close(); received);


}

} UDPServer.java: A server Pro


II gram.
illPort java. net.*;
. part java. io. *;
111 ·

tication h.u bliC class UDPServer


pil . ' . .
. ~~

public static void main( ·.· ·


{ . ··. . .• . . ,: : . . :-.' . .String args[ ]) throw, IOExceptton

- -· -=

--~b¥t~~] . buf ~~" new byte(256};

~-, :' -:.-__/t ~reate __datagram socket ·


on -_ DatagramSocket socket =new DatagramSocket(4445);
-. -. .

. .-.;,. >i,-t: I/ receive . ~equest :


DatagramPacket packet / new DatagramPacket{buf, buf. length);
socket. receive(packet);
. InetAddress address .• packet.getAddress();
int port = packet.getPort{);
.. String s • "Hello";
calhose); buf =- s , getBytes ();
5)i
ress, 4A4 • ddress• and •port•
the client at a
// send the response to b f .length, address, port);
. ramPacket{buf, u
packet • new oatag
socket.send(packet);

I /Close socket
socket. close();
}
•• •• 1. I

240 Adv:111Cl'dJ.1va r,\,,o,:riunmin,'l. ,/ Java ,.. .


1'f., petP j.O • '
~f "". "' •
:I" t j' 11et . ,
l ja"a • lJ~LDE
/ ,1ass
il'
;
stati'
.f'1i'
(
trY
{ UR
,.11ew
~rl ").
~.11tS•~t1"1 '
r system,c
system-~
system.~
&6 WOIUUNG WITH URLs
system.~
L"RL is the acronym for Urn•torm Resource Locator• It is a reference (an address). to a resource on
the Internet httpj/tutorials.ienkov.comtjava-networkinuudp-data~ram-sockets.html IS
}
an example of
CRL. A URL contains many informations such as catch(Exce
1. Protocol: In above example, http is the protocol.
2 Server name or IP Address: In above example tutorials.jenkov.com is the server name. System.
3. Port Number: It is an optional attribute. It can be specified by writing after domain
name as: ht · tutorials. 'e11kov.com:8Q ·ava-networkin ud -data ram-sockets.html 80 is the
port number.

4. File Name or directory name: In this case, /java-networking/udp-datagram-sockets.html is


the file name.
Ii!!
Java programs that interact with the Internet also may use URLs to find the resources on the
Internet they wish to access, Java programs can use a class named URL in the java.net package Protocol: http
to represent a URL address. The java.net.URL cla~ provides many methods. The important
.
methods of URL class are given below: Name: tutorials.
Method Nlllnber:-1 1

Description
public String getProtocol() Naine: /iava-net,
It returns the protocol of the URL
public String getHost()
It returns the host name of the URL - URI.conn,
public String getPort()
public String getFile() It returns the Port Number of the URL - '-• tJR,,..
,lion.~~e
public URLConnection
openConnection()
It returns the file name of the URL
It returns the instan Of U , . ;;-
- ~ It .l'his das
~ 18 llot Pol
URL. ce RLConnection associated with
. ~
~-
11uRLDemo. Java
j,r1port java . io . *;
jtllPort java. net.* ;
ptJbJiC class URLDemo

ublic stat 1· c VOid


{P main(st .
r1ng[]
try args)

{
URL url=new URL("
wckets.html")
. ,· http://t utorfals
System. out pr· . jenkov
- -corn/
system. out · lntln(
. Protoc l
11 hva
.
·network ing/ud
• printl o . "
. System.out • n("Host Na • +ur1.ge1:,,,,, ,.,,,.,,,..
' S .pr1ntln("P me: "+ur1 oc010) •
.an address) t ~ . ystem. out. p . Ort Numb • " .getHost()) · '
O
1Qs:ketS,h fm[ ' a resOlJrce } r1nt1n("Fi er. +ur1 '
- 1s an ex on . . . le Name .' - · ,getPort())
cilllp!e ~ .
t ' +Url. , j
ca ch(Excepti - - , . :·.·· getF1le())·
( • on e) ,

D.com is the server name


System -·
Id b . } . -~ut.println(e);
y writing after domam
fl.gram-sockets.html, 80 is Iii!
}

lp-datagram-sockets.htm/~ }
2!ln>J!!
find the resources on iw Protocol: http · ·· · ·
RL in the java.net pac~ Host Na · -
methods. The unpartad Port N me: tutorials.jenkov.com
umber: -1
FileName· ;· . ..
[
• 86 . Java-networking/ udp-datagram-sockets.html
1

,--------- . aass
____,,) n-.' ·1 URLConnection · , ·
.----- I••• !JIU~onneclion class
./1 'PJ>lication.
.----------/ , .
represents a communication link t,etween the URL and the
~ / lhe liRL. . class can be used to ,ead and write data to the specified """"" refefred by
' ""'te th 1I IS not possible to instantiate !he IJRLConn"ffi'" class dn,ctly. Instead we have to
beiow, e liRLConnection via th, openConnt<tionO Jl1dhod ol URL class- Syntax for t!us givffl ~
Public UR LConnection opencon~ectiOIIO
th
'°"' IOExceptlon{ l
242 Advanced Java Pmgmmming

110ds ' we can() display all the data of


The URLConnection class provides many met thod return a Webpa
. Th tlnputStream me s all th d 8e h.
usmg the gctJnputStreamO method. e ge e ata "Y
d displayed . of ti.
specified URL in the stream that can be rea d an ""
Example
import java.io.•;
import java.net.•;
public class URLConnectionEx
{
public static void main(String[] args)
{
try
{
URL url cnew URL("http://www.tutorialspoint.com/
java/java_networking.html");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getinputStream();
int .i;
'
_while((i=stream.read())!=-1)
{
System.out.print((char)i);
}
}
catch(Exception e)
{
System.out.println(e);
}
} :,=Ine
}
Sample Output
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{

private Serversocket serversocket·


public GreetingServer(int port) th,
{ · · rows IOException ·
serverSocket = new 5 . .
erversocket(port)·
serverSocket.setSoTi ,
} meout ( 10000) j _

................." ........
l

JI'a JttetAddress class r•pre ··


thods to get the IP of sents an IP
ll'e k any h ad
,.,,,.JaceboO .com etc. CommOnly Ostunallle for dres,_
exa 11,e iav
~,thod SOd llletho ~Pk Ww,,,.'"•et.lnetA
Descrj . ds of In •Javat o· ddress cl
p int.corn• wwwass PTovid ~
etAddre"<las
,-lli'tByName(String host) Ption
It 1S· static s are: ·80ogle.corn,

containin method and


g Loca1 Ii returns
getLoCaIHostQ It return s the . ost IP and namethe instanee of Inet
name and 11\s!ance of Add,..,
address lnetAdddr
getttostNameQ It returns ess containin
->tHostAddressQ
.5<-u the host name of ,L_ g local host
r-___. . . : . . .___
• I It returns th uie IP add

getAllByName(host) I e IP address in strin ress


~-:-_ ___.:..._..:..__ _~tt rreturns gformat
Example __an array of IPs about the host

ilJ)Ort java. io. * ;·


ilpOrt jaVa •net •.• J•' -c ,;X, ..- ;·,- .-..:c - - .-~

class InetDemo J .· ·:_.:.

{
{public -static
.• -void
- ' main(St r i ng [ J args) thNlWs Exception

InetAddress ip;
iJ>=InetAd · · · · · ·· -
dress· getByName("www.sharesansar.com");
System. o~t. println("Host Name: "+ip.getHostNa.e());
S_ystem. out. println ( "IP Address: •+ip. getHostAddress O);

Host Name: www.sharesansar.corn


. IP Address: 74.208.195.88 -"· ·-• .-. ..,, fi•'' ,.-t :· . .-- ... .,....

.,_ ·,. . , .
•, _ ."I.D, _,,.c. , •. ~-- .. •, . rnessage& (emails).
,,_ d ,led'"""
~ J lMail is an API that is used to cornPod ... t and platfotlll·l.ll~epe ckages contains the
"" J.. . se, .,rite ,nd ,ea . ,,dent &•-k for

~ ••aMa;J API provides proto"'I•ind•!""


~. g and rece· . ·1s The
"" -·" d•'""' P'
,JI ,nd ,.,.,,.,..,...,
applied to
any """' """ "''
J. a~a%-ot
,.d

~~ cias
i.o 111
1vmg ma• . . facility call ..,..
ses of JavaMail APL The JavaMa1l
244 Advanced Java Programming .,e

~,
hanks f • (41.
. tification such as t or your interest
.
at the time of registenng h
t e user (for sendin g no ·1 1'd)
, sen ding notific
. rJO~
. th
assword to e users ema1 ati to Tl\~
site), forgot passw ord (sen d mg P ons I
ot
important update s etc. ~e
.
If we use Java 2 Platform, Enterprise
.. a
· Edition 2
EE) 1 3 it includ es JavaMail, so no add.in
· '
r.(;;i
. J Platfo rm, Stand ard Editio n 02SE) 1.l ol\al
~
setup is required. If, however, we . r. u ~ g ~
2
a plications, we need to down load and -. ~
7 setf~
upwar ds, and we want email capability for our P
the following:
ltlstaJJ ~
ftddl
• JavaMail API
• Java Activation Framework ~
. . .
wn1 d d files We will find a numb er of Jar files. We nee(! t ft""'
To install, simply unzip. the. do. ~ e
add mail.jar and activation.Jar files m our CL
~PA TIi.' It looks like below : o se1sl
C: \ Program Files\ Java\ Apps \ ma~l.ja? . · · ·_
_ _
.,irj
C: \ Program Files\ Java\ Apps \ achvahon.Jar · ·
£ti~

There are following three steps to send email using ~avaMail.


They are as follows: ~
L Get the session object
It stores all the inform ation · of host like . h~st .: name ,
The jrnxu.mail.Session class pro;id es two methods to
usern ame,. password etc.
:j
get the object of session,

1
Session.getDefaultlnstance() method and Session.getlnstanceO method.
We can use any
metho d to get the session object. Method of Session class are: l.
The.
Methods Descr iption - ,i
Session getDefaultlnstance(Properties p) Returns the default session
-
meth,
Session getDefaultlnstance(Properties p, Returns the default session
Authenticator a) >.t~
Session getlnstance(Properties p)
Returns the new session Strid
I Session getlnstance(Properties p, -
Returns the new session
Authenticator a) Bend
I
!
Example of getDefaultlnstance() method --
Properties properties•new Properties();
Session session•Session.getDefaultlnstance(properties,null);
2. Comp ose the·messa ge - . ,__ < ...... -_.,.. " ' -~ ..::>-N .... ~ . ~ • . ·-

The javax.mail.Message class provi d~ methods to · com ~ the


~essa ge. -But it is all
abstract class so its subclass javax.mail.internet.MimeMessage
create the message, yo~ need to pass session object in MimeMess
class is· mostly
age class constrU
used;
For example, · · ·
MimeMessage message~n Netw
ei., Iii.me,., Ot(rjl'\
..row message object h ess 09e( &Pro&talll .
!" as bee sesst lll1n ~
),liDteMessage class Ptovictes n <reateq b ••); 80 a,,,.,, 8) 24:i
~'irneMessage class: lll.a.ny ...... th \J.t to st
iv• ••1e Od ore i

Methods
s. let s see
1
nforrnation .
llleth II\ th.is obj
setFrom(Address address) · O<ls . ect
Provided by the
addRecipient(Message.RecipientT
Address address) YPe

addRecipients(Message.Recipientr
Address[] addresses) yPe dress to the

setSubject(String subject)
resses to the
setText(String textmessage)
der field ·
It is use to set the .
. text as the
Example to compose !he message using text/plain MIME message content
type.
Mim:.~~s_age ~essag~=n~ MimeMess:ige(session);. .
0
message.setFrom(new InternetAddress("son.OOJ. • I@ : ··
. _ a1swa sss1t.org"));
message.addRecipient(Message.RecipientType.To,
new InternetAddress("
~
• ~
!-
[email protected]"));
~
: ::- ;. ':.."I; -
' '

ssword e1r. message.setHeader("Hi, everyone"); ~


of sessioo,
message.setText(" Hi, This mail is to inform you:.. ");
:an use any
1 Send the message ·,~;. . .. . :. -- -- . r--.. : .

The javax.mail. Transport class provides method to send the message. Commonly used
methods of Transport class are: - · · "
- ,·, . :

Methods Description
send(Message message) It is used send the message
d send the message to the given addresses
send(Message message, Address[ 1address) It is use
...
&ample to send the message ·
Transport.send(message); · .
/~..- · M ii API .
'"-'«lllple of sending email using Java a
1-i>ort java. util. •;
1-r>ort javax.mail.*;
~rt javax.mail.internet.*i
tl rt javax.activation.*; icator
ass SendEmail extends Authent
4J-;

248 Adva nccdJ,wa Programmins


{ d@gmail ,com";
static Stri ng f rom • "arj unsau
static String pass• "a rj un@2039 ";
InternetAddress t o; ] args) throws MessagingException
public static void main(S t ring [
{
// Get the session object System.getProperties().
;
tis properties •
Proper e th" "true");
t("mai 1.smtp.au '
propert i es.pu
"mail.smtp.startt1s.ena ble" , "true"),·
properties.put( . )
//starts TLS ( tranport layer security
" il smtp.host", "smtp.gmail.com");
properties. put ( ma · .. .. .. .
properties. put ( "mail. smtp. port , 587 ) ,
properties.put("mail.sm tp.user", from);
properties.put("mail.sm tp.password", pass); .
Session session = session. get Defaul tlnstance( properties};

//compose the message


MimeMessage msg = new MimeMessage(session);
11-! abstract
mech2
msg.setFrom(new
IntemetAddress(•[email protected]")); · ' ' ~ the architectw
to= new InternetAddress("arjuns [email protected]"); • An applica·
■sg. addRecipient (Message. RecipientType. TO, to); ,
by the appj
msg.setSubject("Test Java Mail"); , .: . underlyin8
msg. setText ("Hello, . this . is example of sending
email•); • A service-d
languages,
// Send message isUSed to 11
Transport transport a session .•getTransport(•smtp•);
transport. connect ( "smtp. gmail. com", from, pass);
transport.sendMessage (msg,msg.getAllRecipi ents()); "ttii,
System• out. println ( "message . sent successfully.••·"); -- aPJ>lication i
~rJ. the nuznbe1
}
}
,.\d~ .
Output ~"t ~-Java:
1'lll't :Ja"a • ~,et
~-- I
message sent successfully....
i.i. :Ja"a 1 .
l'lll't .. Q ~
la"a •
•\lttJ
·~··. ·-:· ..
~,
.,,,-
.,
!,g,1,,~a Mail. Architecture 1·
Network·111
&Pr
og,all11l1i11g Q
Chapter 8)
- -
~• i,ove the Java app 1cation use8 J 241
·J a avaM •
L' :J'. figure illustrates the architectu ail APJ to c
,i,11•1llS re of Javal6 . ornp05e, se nd and
~~' ,v1a1(: .
receive emails. The
Java A
PPIICatlon

();

tr-ue ");
r)

com");

·
nce(pl"Operties};

fig. 8.4 Java mail architecture.


ision);
lre abstract mechanism of JavaMail API is similar to other APis, such as JDBC, JNDI etc. As
!8!11 the architecture diagram above, JavaMail API is divided into two main parts:

• An application-independent part: An application-programming interface (API) is used


by the application components to send and receive mail messages, independent of the
underlying provider or protocol used.
•le of sending • A service-dependent part: A service provider interface (SPn speaks the protocol-specific
languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It
· ·1 · t O the iava platform.
IS used to plug in a provider of an e-ma1 service r
~ ..... .
lmtp" >; ~ ..._wim-amrii•• 10UJ110N
1
from, pass); In this . . om client and reads them and then calculates
aPPlication server requests two numbers fr . h . d by client and presented to
~ecipients() ).\
SUin of the numbers and provides result to the client, whic IS rea
cessfullY··· ~-
// AddSe
llpo rver.java: Server program.
~ java.net.•;
i... java.10. •;
..,iort j
ava.ut11. •;
!G AdvanccdJnva Prognmimir\~
public class AddServer
{
public static void main(String args[]) throws IOException

{ l
II Register service on port 1254
serversocket s . new serversocket(1254);
Socket sl•s.accept(); // Wait and accept a connection

II Get a communication strea~ associate~ with the socket


Scanner in=new scanner(s1.getinputStream());
PrintWriter outs= new PrintWriter(sl.getOutputst rea"'() ,
true);
Scanner sc•new Scanner(System.in);
String ss=null, rs=null;

outs.println("Enter First Number");


int a=in. nextint () ;.. -· _ _ · - : " ·
outs.println("Ente~ _Second Number");
int b=in. nextint (); · · } . ..

-
int r=a+b·I
l
outs. println("Sum=';~r);

I I Close the conn~cti~n~. bu~ - not the server socket


outs. close O;
in. close();
st.close();
} •\

}
II AddClient.java: C1ient program.
import java.net.•;
import java.io.•;
import java.util •·, .
public class AddClient
{

public static void main(St ring args[])


throws IOException
{
Nctwo1t
111&P1n,..
I I Open Your vyanill\1118 0 -
Socket s 1 ,.., connection t Chapter I\) 241
- new So k oa
c et (,, l Servel"
I I Get an input f ocalhost \ ~i:!)
~ort 12s4
S ile handl
canner in==new S e f roni th·e socket
P
• •
r1ntWr1ter outcanner( Sl •Ret rnputs and read th@
true ); S:a new trean,() ),
Printwr1t '
. Scanner s<=new Sc a "( ' 1•&eto.tP<ltStreao(),
nner(system , in);
String msg::: in.nextLine() ,
System. out. println (msg). '
int a=sc. next Int(); '
outs. println(a);
msg= in. next Line();
System. out. println(msg);
int b=sc.nextint();
outs. println(b);
msg,:; in~ nextline();
System. out. println(msg);

in. close();
_ outs. close();
_,:. .
· st.close();
; Ji

}
Output

l;4; J
l

I
258 Advanced Java Programming

1. Define the terms IP address and port. Differentiate between


TCP and lJDp '
programming point of view. froiti
2. Describe the steps to write client and server programs by using
UDP protocol With hritf
description of each step.
3. W'hat is meant by socket? Discuss the major classes used in netwo
rk prograrnlltirig
briefly.
4. Write the steps for writing client and server programs _using TCP
protocol and discuss
each step briefly. ·
5. What is URL and what are its components? Write a program
to extract different
components of a URL and display them.
6. What is the importance of URLConnection class? ~xplain with suitab
le Java code.
7. What is meant by Inet address? Discuss d_ifferent methods provided
by lnetAddres.s class
with suitable example.
8. What is the purpose of Java mail API? Explain the steps u~ in sendi
ng email by using
Java mail APL
9. ~ Java mail architecture with suitable diagram
and explain its components.
10. Write and program where server calculates factorial of a number n
and sends result to the
client provided that n should be supplied by client.

· □□□

You might also like