Network Programming-Min
Network Programming-Min
NET\VoRK Pao
· · ··.' · · : . .. . · .·.
0
RAMMINc
Chapter Outlines
~~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, ....)
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
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
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,
-"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
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~~
{ " ." ' ,' ' , - . .. . ..
/ 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(); ·•~ · }
riable,
ket, ts' ~Q \
ver program.
I1ser
. rt java. net.*;
)."'° rt . *;
java. 10.
illPort java. ut1• 1 . *;
1-i>O
c1ass MsgServer .
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
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
- -· -=
I /Close socket
socket. close();
}
•• •• 1. I
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
{
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) ,
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
................." ........
l
{
{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);
.,_ ·,. . , .
•, _ ."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
~~ 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~
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 .... ~ . ~ • . ·-
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; -
' '
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
...
&le 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-;
();
tr-ue ");
r)
com");
·
nce(pl"Operties};
{ l
II Register service on port 1254
serversocket s . new serversocket(1254);
Socket sl•s.accept(); // Wait and accept a connection
-
int r=a+b·I
l
outs. println("Sum=';~r);
}
II AddClient.java: C1ient program.
import java.net.•;
import java.io.•;
import java.util •·, .
public class AddClient
{
in. close();
_ outs. close();
_,:. .
· st.close();
; Ji
}
Output
l;4; J
l
I
258 Advanced Java Programming
· □□□