Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
IT E74 WEB TECHNOLOGY
Department Of Information Technology 1
UNIT IV
Streaming – Networking Principles – Sockets for Clients - Sockets for Servers – Protocols handlers – ontent
handlers – Multicast sockets – Remote method invocation.
4. 1. Streams:
Input is data going into a program; output is data flowing out of a program. I/O is frequently done using I/O streams. A stream
is a sequence of data flowing from a source to a destination . I/O streams can be connected to a wide variety of data sources and
destinations. The core Java language does not have any I/O methods. For a program to do I/O, it must import an I/O package called
java.io. Data for a program may come from several sources .Data created by a program may be sent to several destinations. The
correspondence between a program and a data source or destination is called a stream. An input stream handles data flowing into a
program. An output stream handles data flowing out of a program
Output Stream Input Stream
Data Source
Data Destination
A processing stream operates on the data supplied by another stream.Often a processing stream acts as a buffer for the data
coming from another streams.A buffer is a block of main memory used as a work area . For examples, disk file data usually is
delivered by the operating system in block of 512 bytes at a time. Usually this data is buffered and delivered to a program in more
suitable sizes. In the following , the keyboard sends data to the Input stream system.in,which is connected to a BufferedReader
stream.system.in is a stream object that the Java system automatically creates when the program starts running
BufferedReaderstdin=newBufferedReader(newInputstreamReader(system.in));
BufferedReader inputstreamReader inputstream
Stdin system.in
The data is transformed along the way. The raw bytes from the keyboard are grouped together into a string object that the program
reads using stdin.readsLine() .
Types of streams:
A stream object may be
An input stream or an output stream,
A processing stream or an ordinary stream,
A character-oriented stream or a byte-oriented stream,
Connected to variety of sources or destination
There are many types of streams.For example , a stream might be an “input, character –oriented ,processing stream”.
Another might be “output,ordinary ,byte-oriented stream”.Not only are there many types of streams,there are also manay way to
connect them together .The digram shows the top of the hierarchy for the java.io packages. The dotted clouds are abstract classes.
They act as base classes for specialized streams.
byte –oriented streams character –oriented streams
Java Program
1.234
23.90
-10.30
93.22
Java Program
Object
Input
Stream
Writer Reader Output
Stream
IT E74 WEB TECHNOLOGY
Department Of Information Technology 2
Types of Streams
Streams are byte-oriented or character-oriented. Each type has input streams and output streams.
Byte -oriented streams:
Used for general-purpose input and output.
Data may be primitive data type or raw bytes.
Character-oriented streams:
Specialized for character data.
Transforms data from/to 16-bit Java char used inside programs to
UTF format used externally.
Character streams and Byte streams :
Character streams are intended exclusively for character data. Byte streams are intended for general purpose input and
output. Fundamentally, all data consist of patterns of bits grouped into 8-bit bytes. So, logically all streams could be called byte
streams. However, streams that are intended for bytes that represent characters are called character streams and all the other are
called byte streams. Character streams are optimized for character data and perform some other useful character-oriented tasks. The
source or destination of a character stream is often a text file, a file that contains bytes that represent characters.
InputStreams :
Inputstream is an abstract class from which all byte-oriented input streams are derived. Its descendant classes are used for
general-purpose input (non-character input).These streams are aimed at delivering data to a program in groups of 8-bit bytes . The
bytes can be grouped into the size necessary for the type of data. For examples, if a disk file contains 32-bit int data, data can be
delivered to the program in 4-byte group in the format as Java primitive type int. For different input streams is given as below.
InputStreams defines the following methods for reading bytes and arrays of bytes:
1. Public abstract int read() throws IOException
2. Public int read (byte cbuf [ ] ) throws IOException
3. Public int read (byte cbuf [ ] , int offset ,int length ) throws IOException
4. Public long skip (long n) throws IOException
5. Public int available ( ) throws IOException
6. Public void close ( ) throws IOException
Concrete subclasses of Inputstreams use these methods. For example, a FileInputStream reads data from a file . A ByteArrayInput
Stream reads data from an array of bytes. For instances the following code shows how to use the FileInput Stream.
Import java.io.*
Byte Array
Input Stream
Input Stream
File Input
Stream Piped Input
Stream
Object Input
Stream
File Input
Stream
Buffered
Input Stream
Data input
Stream
IT E74 WEB TECHNOLOGY
Department Of Information Technology 3
Public Class Demo
{
Public Static Void main( String [ ] args) throws IOExecption {
File inputFile= new File (“ text1.txt”);
File InputStream in=new FileInputStream (inputFile);
Int c;
While ( (c=in.read ( ) ) !=-1)
System.out.println( c);
In.close()
}
}
OutputStreams:
Outputstream is an abstract class from which all byte-oriented output streams are derived. Its descendant classes are used
for general purpose (non-character output). These streams are aimed at writing groups of 8-bit byte to output destinations. Byte
are in the same format as Java primitive types. For example, 4-Byte groups corresponding to type int can be written to a disk file.
For different output streams is shown as below.
Outputstreams
OutputStreams defines the same methods but for byte as mentioned below :
1. Public abstract Void write (int c) throws IOException
2. Public Void write (byte cbuf [ ] ) throws IOException
3. Public Void write (byte cbuf [ ] ,int offset,int length ) throws IOExecption
4. Public Void flush( ) throws IOExecption
5. Public Void close ( ) throws IOExecption
The following code demonstrate the use of FileOutput Streams.
Import java .io.*;
Public class copy {
Public static void main (string [ ] args ) throws IOExecption {
File inputFile =new File (“text1.txt”);
File outputStreams =new File (“text2.txt”);
FileInputStreams in =new FileInputStreams (inputFile );
pipeoutputstream
m
outputStream
ByteArrayoutput
stream fileoutputstream
filteroutputstream objectoutputstream
bufferedoutputstream
am dataoutputstream printstream
IT E74 WEB TECHNOLOGY
Department Of Information Technology 4
FileOutputStreams out =new FileOutputStreams (outputFile );
int c;
while ( (c =in .read ( ) ) !=-1 )
out.write(C);
in.close ( );
out.close ( );
}
}
Filter Streams:
The java .io packages provides a set of classes that defines and partially implement filter streams .A filter streams data as it is
being read from or written to the stream .The filter streams are FileterInputStream or FileterOutput Streams. A filter stream is
constructed on anoyher stream (the underlying stream ). The read method in a readable filter strream reads input from the
underlying stream,filter it, and passes on the filtered data to the caller . The write method in a writable filter stream filters the data
and then writes it to theUnderlying stream. The filtering done by the filter streams depnds on the stream . Some streams buffer the
data,some count data as it goes by, and others convert data to another form .The filters come in two forms the filter streams and the
readers and writes .
Most filter streams provided by the java.io packages are subclasses of FilterInputStream and FilterOutputStream and are listed
here :
DataInputStream and DataOutputStream
BufferedInputStream and BufferedOutputStream
LineNumberInputStream
PushbackInputStream
PrintStream (this is an output stream ).
To use a filter input or output stream,attach the filter stream to anoyher input or output stream when it is created. For example, a
filter stream can be attached to the standard input stream, as in the following code.
BufferedReader d =new BufferedReader (new DataInputStream (system .in );
String input ;
While ( (input=d. readLine ( ) ) != null )
{
....//do somthing
}
The chain in the above code can be rewritten as
DataInputStream in = new DataInputStream (system.in );
BufferedReader d =new BufferedReader (in );
The reading and writing can be done with respect to the last stream in the chain.
Buffered streams
BufferedInputStream bis =new
BufferedInputStream (myInputStream ,1024 );
.....
bis . read ( ); // buffers reads for efficiency
BufferedOutputStreams will cache output and not perform an actual write ( ) until the buffer is full. The buffer can be clearedby
calling flush ( ).
Readers and Writers :
Readers and Writer deal with character streams .These are abstract classes . A program must use classes derived from them . For
example, a BufferedReader is a Reader.
IT E74 WEB TECHNOLOGY
Department Of Information Technology 5
Character streams are optimized for handling character data. They also translate between the internal format used by Java
program and external format used for text files. Inside a Java program character data is represented with the 16-bit char data type.
The character of a string use the same 16- bit code. On a disk file,character are represented in a format called UTF. This format
uses one, two or three bytes per character and is intended to be a universal format one format for all text files in any language
anywhere in the world .
UTF stands for “Universal character set Transformation Format”, Usually a UTF text file is identical to an ASCII text file.
ASCII is the standard that most computers have used up until now . A file created with Notepad is an ASCII text file, However, a
UTF text file can include non-ASCII character such as Cyrillic, Greek, and Asian character. By reading and writing UTF files, Java
programs can process text from any of the world‟s languages .
Writer:
Writer is an abstract class from which all character-oriented output streams are derived. All these streams are aimed at
receving 16- bit char data from a program, and sending it to another destination, which may use a different character format (such a
UTF format on a disk file ).
All these classes are character-oriented output stream. The different writer classes are given as below
Reader:
Reader is an abstract class from which all character-oriented input streams are derived. These streams are aimed at delivering
16-bit char data to a program although the source of the data may be in a different formay(such as UTF format on a disk file).
All these classes are character-orinted input streams.Reader contain these methods for reading character and arrays of characters .
int read ( )
Writer(abstract
)
charArraywriter
stringwriter pipewriter
Filterwriter
(abstract)
Filewriter
printwriter
Outputstrem
writer
writer
bufferedwriter
reader
charArrayreader
bufferedreader
stringreader
inputstreamReader
pipereader
Filterreader(abra
ct
filereader
IT E74 WEB TECHNOLOGY
Department Of Information Technology 6
int read (char cbuf [ ] )
int read (char cbuf [ ], int offset, int length )
writer defines these methods for writing characters and array of characters:
Int write(int c)
Int write(char cbuf [ ])
Int write(char cbuf [ ],int offset,int length)
Data streams:
The data input stream and data output stream classes provide methods for reading and writn java‟s primitive data types and
strings in a binary format. The binary formats are used to exchange data between two programs or networks or pipes. The data
output stream class offers the following methods:
1.public final void writeBoolean (Boolean b) throws IOException
2. public final void writeByte (int b) throws IOException
3.public final void writeShort (int s) throws IOException
4.public final void writechar (int c) throws IOException
5.public final void writeInt (int c) throws IOException
6.public final void writeLong (long l) throws IOException
7.public final void writeFloat (float b) throws IOException
8.public final void writeDouble (double b) throws IOException
9.public final void writeChars (String s) throws IOException
10.public final void writeBytes (String s) throws IOException
All data is written in big-endian format and in two‟s complement form. Datainputstream offers 9 classes along with normal
read(),available() and close() method.
1.public final Boolean readBoolean() throws IOException
2. public final byte readByte() throws IOException
3.public final char readChar() throws IOException
4.public final short readshort() throws IOException
5.public final int readInt() throws IOException
6.public final long readLong() throws IOException
7.public final float readFloat() throws IOException
8.public final double readDouble() throws IOException
9.public final string readLine() throws IOException
Object streams:
Traditionally, there should be some way of encoding the object as a sequence of data values belonging to the primitive types,
which can be output as bytes or characters. This is called serializing the object. This is called serializing the objects. This process
can be done with the help of java‟s classes objectinputstream and objectoutputstream. These are subclasses of inputstream and
outputstream that can be used for writing and reading serialized objects.
ObjectInputStream and ObjectOutputStream are wrapper classes that can be wrapped around arbitrary inputstreams and
output streams. This makes it possible to do object input and output on any byte-stream. The methods for object I/O are
readobject(), in objectinputstream and writeobject(object obj),in objectoutputstream. Both of these methods can throw
IOExceptions. Note that readobject() returns a value of type object, which generally has to be typedcaasst to a more useful type.
Objectinputstream and objectoutputstream only work with objects that implement an interface named serializable.
Furthermore, all of the instances variables in the object must be serializable. However, there is little work involved in making an
object serializable interface does not declare any methods. It exists only as a marker for the complier to tell it that the object is
meant to be writable and readable. Many of java‟‟s standard classes are already declared to be serializable,including all the
component classes in swing and in the AWT(abstract window toolkit). This means,in particular,that GUI(graphical user interface)
components can be written to objectoutputstreams and read fraom object inputstreams.
IT E74 WEB TECHNOLOGY
Department Of Information Technology 7
4.2. NETWORK PRINCIPLES (or) NETWORK CONCEPTS
Network
A network is a collection of computers and other devices that can send data to and receive data from each other, more or less in
real time. A network is normally connected by wires, and the bits of data are turned into electromagnetic waves thatmove through the
wires.
Node
Each machine on a network is called a node. Every network node has an address: a series of bytes that uniquely identify it
Host
Host refers to a networked general purpose machine rather than a single purpose device.
Protocol
A protocol is a set of rules defining how computers communicate how address work, how data is split into packets etc.
The Layers of a Network
The Host-to-Network Layer
The host-to-network layer defines how a particular network interface, such as an Ethernet card or a PPP connection, sends IP
datagrams over its physical connection to the local network and the world.
The Internet Layer
A network layer protocol defines how bits and bytes of data are organized into larger groups called packets, and the addressing
scheme by which different machines find each other.
Data is sent across the internet layer in packets called datagrams. Each IP datagram contains a header from 20 to 60 bytes long
and a payload that contains up to 65,515 bytes of data. (In practice most IP datagrams are much smaller, ranging from a few dozen
bytes to a little more than eight kilobytes.)
The header of each IP datagram contains these 13 items in this order:
4-bit version number
Always 0100 (decimal 4) for current IP; will be changed to 0110 (decimal 6)
for IPv6, but the entire header format will also change in IPv6.
4-bit header length
An unsigned integer between and 15 specifying the number of 4-byte words in the header; since the maximum value of the header
length field is 1111 (decimal 15), an IP header can be at most 60 bytes long.
1-byte type of service
A 3-bit precedence field that is no longer used, 4 type-of-service bits (minimize delay, maximize throughput, maximize reliability,
minimize monetary cost), and a bit. Not all service types are compatible. Many computers and routers simply ignore these bits.
IT E74 WEB TECHNOLOGY
Department Of Information Technology 8
2-byte datagram length
An unsigned integer specifying the length of the entire datagram, including both header and payload.
2-byte identification number
A unique identifier for each datagram sent by a host; allows duplicate datagrams to be detected and thrown away.
3-bit flags
The first bit is 0; second bit is if this datagram may be fragmented, 1 if it may not be; third bit is if this is the last fragment of the
datagram, 1 if there are more fragments.
13-bit fragment offset
In the event that the original IP datagram is fragmented into multiple pieces, itidentifies the position of this fragment in the original
datagram.
1-byte time-to-live (TTL)
Number of nodes through which the datagram can pass before being discarded; used to avoid infinite loops.
1-byte protocol
Six for TCP, 17 for UDP, or a different number between and 255 for each of more than one hundred different protocols (some quite
obscure);
2-byte header checksum
A checksum of the header only (not the entire datagram) calculated using a 16-bit one's complement sum.
4-byte source address
The IP address of the sending node.
4-byte destination address
The IP address of the destination node.
In addition, an IP datagram header may contain from to 40 bytes of optional information used for security options, routing records,
timestamps, and other featuresJava does not support. Consequently, we will not discuss these here. The interested reader is referred to
TCP/IP Illustrated, Volume 1, by W. Richard Stevens for more details on these fields.
The structure of an IPv4 datagram
IT E74 WEB TECHNOLOGY
Department Of Information Technology 9
The Transport Layer
The transport layer is responsible for ensuring that packets are received in the order they were sent and making sure that no data is lost
or corrupted. If a packet is lost, then the transport layer can ask the sender to retransmit the packet. There are two primary protocols at
this level. The first, the Transmission Control Protocol (TCP), is a high-overhead protocol that allows for retransmission of lost or
corrupted data and delivery of bytes in the order they were sent. The second protocol, the User Datagram Protocol (UDP).
The Application Layer
The layer that delivers data to the user is called the application layer. The three lower
layers all work together to define how data is transferred from one computer to another. The application layer decides what to do with
that data after it's transferred.
IP Addresses and Domain Names
Every computer on an IP network is identified by a 4-byte number. This is normally written in a format like 199.1.32.90, where each
of the four numbers is one unsigned byte ranging in value from to 255.
Ports
Each computer with an IP address has several thousand logical ports (65,535 per transport layer protocol, to be precise).
Each port is identified by a number from 1 to 65,535
The Internet
The Internet is the world's largest IP-based network
Internet Address Classes
Internet addresses are assigned to different organizations by the Internet Assigned Numbers Authority (IANA),[1] generally acting
through intermediaries called ISPs
Firewalls
The hardware and software that sits between the Internet and the local network, checking all the data that comes in or out to make sure
it's kosher, is called a firewall.
The most basic firewall is a packet filter that inspects each packet coming into or out of a network and uses a set of rules to determine
whether that traffic is allowed.Filtering is usually based on network addresses and ports.
IT E74 WEB TECHNOLOGY
Department Of Information Technology 10
Proxy Servers
Proxy servers are related to firewalls. If a firewall prevents hosts on a network from making direct connections to the outside world, a
proxy server can act as a go-between.
4.2.2Client/Server Networking
A server process is allowed to listen to a port until a client connects to it. A server accepts many clients at the same port,
although each session is unique.
4.3. SOCKETS:
TCP provides a reliable,point to point communication channel that client-server application on the internet use to
communicate with each other. To communicate over TCP, a cient program and a server program establish connection with each
another. Each program binds a socket to the end of the connection. To communicate,the client and the server each reads from and
writes to the socket bound to the connection.
A socket is one end-point of a two way communication link between two programs running on the network. Socket classes
are used to represent the connection between a client program and a server program. The java.net package provides two classes-
sockets and serversocket-thar implements the client side as well as the sever side of the connection,respectively.
There are two basic types of network sockets on IP networks-those that use the transmission control protocol(TCP) and those
that use the user datagram protocol(UDP).TCP is a reliable protocol in which data packets are guaranteed to be delivered in the
order. If a packet expected at the receiving end of a TCP socket does not arrive in the set period of time,then it is assumed lost,and
the packet requested from the sender again. The receiver does not move on the next packet until the first is received.UDP,on the
other hand,makes no guarantees about delivery of packets, or the order in which packets are delivered. The sender transmits a UDP
packet,and it either reaches the receiver or it does not.TCP sockets are used in the large majority of IP applications.UDP sockets are
typically used in bandwidth-limited applications,where the overhead associated with resending packets is not tolerable. A good
example of this is real-time network to be played in real times then there is no point in resending a late packet. By the it gets
delivered it will be useless since the audio track must play continuosly and sequentially, without backtracking.
The socket class is used for creating TCP connections over an IP network. A socket is typically created using an Inetaddress
to specify the remote host, and a port number to which the host can connect. A process on the remote host must be listening on that
port number for incoming connection requests.
The InetAddress provides to access host names and IP addresses. The following methods are provided to create InetAddress
objects.
Static InetAddress getLocalhost() throws unknownhostexception this method returns an InetAddress object for the local machine.
Static InetAddress getbyname (string host) throws unknownhostexception
IT E74 WEB TECHNOLOGY
Department Of Information Technology 11
This method returns an Inet address object for the specified host name. the host name can be either pneumonic identifier
such as www.javaregime.com IP address such as 121.1.28.60.This is the only method that can be used by a client to get remote
host‟s details.
The following methods are provided to extract information from an InetAddress object.
Byte[ ] getAddress( )
This method returns an array of byte corresponding to the IPAddress held in the InetAddress object. The array is in network byte
order,i.e. high byte (back to front ) and must be converted to astring before being displayed to the screen.
String getHostName( )
This method returns the host name held in the InetAddress object. If the host name is not already known, an attempt is made to
look it up, if this fails, the address is returned as a string.
The following code demonstrates on how to use the InetAddress class
try {
InetAddress myself = InetAddress .getLocalHost ( );
Output .appendText (“ Local hostname :” + myself .getHostName
( ) + “\n”);
Output .appendText (“Local IP Address : “ + toText
(myself . getAddress ( ) ) + “\n”);
}
Catch (UnknownHost Exception ex)
{ }
Creating Client Sockets:
Asocket is a Java representation of a TCP network connection in the client side. The function of the client socket are to
Connect to a remote host
Send data
Receive data
Close the connection
In order to communicate with a remote host,the Java client must first create a Socket, which will establish the TCP connection.
In doing so , a host name and port number must be specified. There must be a server actively listening to be specified port or the
connection will fail with IOExecption.
The following constructors allow the Socket connection to be established.
Socket (String host , int port ) throws IOException
This creates a socket and connects to the specified host and port. Host can be a host name or IP address and port must be in a range
of 1-65535.
Socket ( InetAddress address , int port ) throws IOException
This creates a socket and connects to the specified port of the host address.The port must be in a range of 0-65535.
The following methods allow the remote host address and local or remote port numbers to be identified. There methods also allow
for the creation of input and output streams.
InetAddress getInetAddress ( )- This method returns the IP address of a remote host.
Int getport ( )-This method returns the port number of the remote host to which the socket is connected .
Int getLocal port ( ) –The local port number which is used tocreate the socket ,is returned by this method .
InputStrem getInputStream( ) throws IOException –This method returns an InputStream that aloe the socket to receive data across
yhe TCP connection. An InputStream can be buffered or standard.
OutputStream getOutputStream( ) throws IOException – This method returns an Outputstreams that allow the socket to send data
across the TCP connection. An OutputStream should be buffered to avoid lost bytes,especially when the socket is closed.
Void close ( ) throws IOException –This method closes the socket,releasing network or system resources being used.
The code below creates a socket to the remote host on the specified port (6005, in this case ):
// Creates the socket
InetAddress addr = InetAddress .getByName(“ Our . remote .host “);
Socket s =new socket (addr, 6005 );
IT E74 WEB TECHNOLOGY
Department Of Information Technology 12
InputStream in = s.getInputStream( );
OutputStream out = s.getoutputstream( );
ServerSocket :
A serversocket is a mechanism by which a server accepts connections from clients across a network . The server opens the
serversocket ana wait or listen for connection from clients . The serversocket class creates a socket for each client connection .The
server handles the connection in the normal manner with input and output streams .The serversocket constructor is used to open up
the connection to a remote client.
Serversocket ( int port,int count ) throws IOException- This construct a serversocket that listens on the specified port,argument 1,of
the local machine. Argument 1 is mandatory and must be supplied. But arguments 2, the outstanding connection requests parameter
, may be omitted or the default of 50 is used. If the count option is used, it specifies the number of outstanding requests that should
be queued by the operatin system before discarding. This option is useful if the server is slow in accepting requests .
The following are the methods that allow accepting the connection when the serversocket is listeningand information about the
server socket is to be obtained.
Socket accept ( ) throws IOException – This method blocks until a client makes a connection to the port on which the serverSocket
is listening .A socket is returned corresponding to the TCP connection from the client.
Void close ( ) throws IOException – This method closes the serversocket. It does not close any of the currently accepted
connections,it only stops additional connections being made by clients.
Int getLocalPort( ) –Returns the integer value of the port on which serversocket is listening.This is useful if the server specifies port
number 0,which means that the operating system assigns the next unused port.
The following code shows the use of serversocket:
Serversocket server = new serversocket (port);
System.out.println (“Waiting”);
Socket clientsocket = server . accept ( );
//Extract the address of the connected user
System .out.println (“Accepted from “ +
ClientSocket .getInetAddress ( ) );
Server .close ( );
Datagram socket :
The UDP socket connectins are created and used through the Datagramsocket and Datagrampacket classes .A
Datagramsocket sends and receives data using UDP packets , represented as datagrampacket objects .Before two computer can talk
to each other over a UDP connection,they both have to have a Datagramsocket connected to a port on their local machines. This is
done by simply creating a datagramsocket object , For example ,
DatagramSocket udp socket = new DatagramSocket ( 6050 );
In this example , a UDP socket is connected to a specific port (6050) on the localhost. We can construct the
Datagramsocket without specifying the port also. An unused port on the local host is usually used. The port number can be found
by using the getLocalport method.
Datagramsocket udpsocket = new Datagramsocket( );
Int portNo = udpsocket . getLocalport ( );
In order for two computers to send data to each other a UDP socket, they must know the host name and port number of each
other‟s socket connection.Therefore, they either have explicitly specified ports for each other and create Datagramsocket using
these port numbers, or they create a socket on a random local port and transmit their port numbers to each other another
connection.
Data is sent over a Datagramsocket using Datagrampacket objects . Each Dtagrampacket contains a data buffer , the address
of the remote host to send the data to, and the port number that the remote computer is listening to. Therefore , to send a buffer of
data to a process listening to port 6050 on host my .host . com, the code given below is added.
Byte[ ] dataBuf = {„h‟, „i‟, „ „, „t‟ , „h‟, „ e‟, „r‟ , „e‟ };
InetAddress addr = InetAddress . getByName (“my . host. Com”);
Datagrampacket P =new Datagrampacket (dataBuf , dataBuf .length, addr,6050);
Udpsocket .send (p);
IT E74 WEB TECHNOLOGY
Department Of Information Technology 13
The remote process can receive the data in the form of a Datagrampacket by calling the receive( ) method on its
Datagramsocket . The received Datagrampacket will have the host address and port number of the sender filled in as a side-effect
of the call.
A simple example:
Here is an example program that repeatedly waits until it is contacted on its server socket.when it is finally contacted,it
starts up a new thread that outputs the first 100 fibonacci numbers.
Import java.net.*;
Import java.io.*;
Import java.lang.*;
Public class fib1
{
Public static void main(String agrv[])
{
Try
{
Serversocket sSoc= new ServerSocket(2001);
While(true)
{
Socket inSoc=sSoc.accept();
FibThread FibT= new FibThread(insoc);
FibT.start();
}
Catch(Exception e)
{
System.out.println(e.toString());
}}}
Class FibThread extends Thread
{
Socket threadsoc1;
Int F1=1;
Int F2=1;
fibThread (socket inSoc)
{
treadSoc1=inSoc;
}
Public void run()
{
Try
{
PrintStream FibOut=new PrintStream(threadsoc1.getoutputstream());
For(int i=0;i<100;i++)
IT E74 WEB TECHNOLOGY
Department Of Information Technology 14
{
Int temp;
Temp=F1;
FibOut.println(F1);
F1=F2;
F2=temp+F2;
}
}
Catch(Exception e)
{
System.out.println(e.toString());
}
Try
{
threadSoc1.close();
}
Catch(Exception e)
{
System.out.println(e.tostring());
}}}
The client side code is
Import java.net.*;
Import java.io.*;
Public class FibReader client
{
Socket appSoc;
BufferReader in;
String msg;
Public static void main(String argv[]) {
Try{
appSoc= new Socket(“where.com”,2001);
in= new BufferReader(new InputStreamreader(appSoc.getInputStream()));
for(int I =0;i<100;i++0
{
Msg=in.readLine();
System.out.println(msg);}}
Catch(Exception e)
{
System.out.println(e.tostring());
}}
IT E74 WEB TECHNOLOGY
Department Of Information Technology 15
Multicast Sockets:
Multicasting is the Internet version of broadcasting .A site that multicasts information is similar in many ways to a
television or radio station that broadcasts its signal. The signal originates from one sources , but it can reach everyone in the
station‟s signal area .Broadcasting is generally suited to any application that requires a number of machines in a distributed group
to receive the same data; for example, conferencing,group mail and news distribution , and network management .Most of the
high- level network protocols only provide a unicast transmission service. That is , nodes of the network only have the ability to
send to one node at a time . All transmission with a unicast service is inherently point-to-point. If a node wants to send the same
information to many desyination using unicast transport services , it must perform a replicated unicast, and send N copies of the
data to each destination.A better way to transmit data from one source to many destination is to provide a multicast transport
service .With a multicast transport service , a single node can send data to many destinations by making just a single call on the
transport service.In a nutshell, multicasting is a datagram based service to send messages to multiple clients .
Multicast Groups and Addresses:
The notion of group is essential to the concept of multicasting. By definition a Multicast message is sent from a source is a
group of destination hosts. In IP multicasting, multicast groups have an ID called multicast group ID. Whenever a multicast
message is sent out, a multicast group ID specifies the destination group. These group ID‟s are essentially sets of IP addresses
called class D. Therefore, if a host wants to receive a multicast message sent to a particular group, it needs to listen to all messages
sent to that particular group. There are three types of IPV4 addresses unicast, broadcast, and multicast. Unicast addresses are used
for transmitting message to single destination nodes. Broadcast addresses are used when a message is supposed to be transmitted to
all nodes in a subnetwork. For delivering a message to a group of destination nodes which are not necessarily in the same
subnetwork, multicast addresses after used.
Classes A, B and c IP addresses are used for unicast messages, whereas class D IP addresses those in the range 221.0.0.1 to
239.255.255.255 inclusive are used for multicast messages.
4.4. WORKING WITH MULITCAST SOCKETS
In java multicasting can be done using the java.net.MulticastSocket class. This is a subclass of java.net.Datagransocket. This
kind of socket is used on the client side to listen for packets that the server broadcasts to multiple clients. The multicast datagram
socket clas is useful for sending and receiving IP multicast packets. Thus, java.net.MulticastSocket and java.net.DatagramPAcket
are used together to implement multicasting in java.
A mulitcastSocket is a UDP DatagramSocket, with additional capabilities for joining groups of other multicast hosts on the
Internet. One would join multicast group by first creating a Multicastsocket, with a desired port, then invoking the joinGroup
method. One can leave a group by using the method leaveGroup.
The following are the two constructors to create the multicast sockets
1. Public mulitcastSocket() throws IOException this allows us to create a multicast socket.
2. Public MulticastSocket (int port) throws IOException this allows us to create a multicast socket and bind it to a specific
port.
There are methods other than the joingroup (Addr) and leaveGroup(addr). The class also provides functions, that set and get
the time to live for DatagramPackets sent to a MulticastGroup, which specifies in how many “hops” DatagramPackets sent to a
mulitcastGroup, which specifies in how many “hops” are needed for the packet to be forwarded on the network for itexpires. They
are seTTl(ttl) and getTTl(ttl). The parameter ttl is an unsigned 8 bit value.
A SIMPLE EXAMPLE
The following source code is a simple example that sends date and time to its multiple clients.
SERVER PROGRAM:
Import java.net.*;
Import java.io.*;
Import java.util.*;
Public class MulitcastServer
{
Public static final int PORT=2001;
Public static void main(string args[]) throws Exception
{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
Address=InetAddress.getByName();
Socket=new MulticastSocket();
IT E74 WEB TECHNOLOGY
Department Of Information Technology 16
Socket.joinGroup{address};
Byte[] data=null;
for {; ;}
{
Thread.sleep(1000):
String str={ new Date().toString();
Data=str.getBytes();
Packet=new DatagramPAcket();
(data,str.length(), address,Port);
Socket.send(Packet);
}
}
}
CLIENT PROGRAM:
Import java.net.*;
Import java.io.*;
Public class MulitcastClient
{
Public static final int PORT=2001;
Public static void main(String args[]) throws Exception{
MulticastSocket socket;
DatagramPacket packet;
InetAddress address;
Address = InetAddress.getByName(args[0]);
Socket=new MulticastSocket(Broadcastserver.PORT);
Socket.joinGroup(address);
Byte[]=data=null;
Packet=new DatagramPacket(data,data.length);
For(;;)
{
Socket.receive(packet);
String str=new String(packet.getData());
System.out.println(“time signal received from”+packet.getAddress()+”time is :”+Str):
}
}
}
4.5 REMOTE METHOD INVOCATION
The java remote method invocation (RMI) system allows an object running in one Java Virtual Machine (JVM) to invoke
methods on an object running in another VM. RMI provides for remote communication between programs written in the Java
programming language. The RMI mechanism is basically an object oriented RPC mechanism.
JAVA RMI ARCHITECTURE
The design goal for the RMI architecture was to create a java distributed object model that integrates naturally into the Java
programming language and the local object model. RMI architect have succeeded by creating a system that extends the safety and
robustness of the java architecture to the distributed computing world.
The RMI architecture is based on one important principle that definition of behavior and the implementation of that behavior and
the code that implements the behavior to remain separate and to run on separate JVMs.
Specifically, in RMI the definition of a remote service is coded using a Java Interface. The implementation of the remote
service is coded in a class. Therefore the key to understanding RMI is to remember that interfaces define behavior and classes
define implementation. The following diagram illustrates this separation.
The RMI implementation is essentially built from three abstraction layers. The first layer is the Stub and skelton layer, which
lies just beneath the view of the developer. This layer intercepts method calls to a remote RMI service.
The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from
clients to the remote service objects. In JDK 1.1, this layer connects clients to remote service objects that are running and exported
on a server. The connection is a one to one link. In the java 2 SDK, this layer was enhanced to support the activation of remote
service objects via Remote Object Activation.
The transport layer is based on TCP/IP connections between machines in a newtwork. It provides basic connectivity, as
well as some firwall penetration strategies.
IT E74 WEB TECHNOLOGY
Department Of Information Technology 17
USING RMI:
There are three processes that participate in supporting remote method invocation
The client is the process that invokes a method on a remote object.
The server is the process that owns the remote object. The remote object is an ordinary object in the address space of the server
process.
The object registry is a name server that relates objects with names. Registered, you can use the object registry to obtain access to a
remote object using the name of the object.
There are two kinds of classes that can be used in java RMI
1. A remote class is one whose instances can be used remotely. An object of such a class can be references in two different ways:
Within the address space where the object was constructed the object is an ordinary object which can be used like any other object.
2. A serializable class is one whose instances can be copied from one address space to another. An instance of a serializable object is
one that can be marhalled.
A class is serializable if it implements the java.io.serializable interface. Subclasses of a serializable, so a subclass of one of them Is
automatically also serializable.
A remote class has two parts: the interface and the class itself. The remote interface must have the following properties:
The interface must be public.
The interface must extend the interface java.rmi.remote.
Every mthod in the interface must declare that it throws java.rmi.RemoteException.
The remote class itself has the following properties:
It must implement a remote interface.
It should extend the java.rmi.server.unicastRemoteObject class.
It can have methods that are not in its Remote interface. These can only be invoked locally.
A SIMPLE EXAMPLE:
1. INTERFACE
The first step is to write and compile the java code for the service interface. The calculator interfaces defines all of the remote
features offered by the service.
Public interface calculator
Extends java.rmi.Remote{
Throws java.rmi.RemoteException;
Public long sub(long a, long b)
Throws java.rmi.RemoteException;
Public long mul(long a, long b)
Throws java.rmi.RemoteException;
Public long div(long a, long b)
Throws java.rmi.RemoteException;
}
2. IMPLEMENTATION
This is the calculatorImpl class:
Public class CalculatorImp1 extends java.rmi.server.unicast
RemoteObject
Implements Calculator{
Public CalculatorImpl1()
Throws java.rmi.RemoteException{
Super();
}
Public long add(long a,long b)
Throws java.rmi.RemoteException{
Return a+b;
}
Public long sub(long a,long b)
Throws java.rmi.RemoteException{
Return a-b;
}
Public long mul(long a,long b)
Throws java.rmi.RemoteException{
IT E74 WEB TECHNOLOGY
Department Of Information Technology 18
Return a *b;
}
Public long div(long a,long b)
Throws java.rmi.RemoteException{
Return a/b;
}}
All of the Remote interface and classes should be compiled using javac. Once this has been completed, the stubs and
skeletons for the remote interfaces should compiled bu using the rmic stub compiler. The stub and skeleton of the example Remote
interface are compiled with the following command:
Rmic CalculatorImpl
3. Client side
A remote method invocation can return a remote object as its return value, but a remote object must be defined in order to perform
a remote methodinvocation. The name of a remote object includes the following information.
The internet name of the machine that is running the object registry with which the remote object is being registered.
The port to which the object registry is listening.
Example
Import java.rmi.Naming;
Import java.rmi.RemoteException;
Import java.net.MalformedURLException;
Import java.rmi.NotBoundException;
Public class CalculatorClient
{
Public static void main(String[]args)
{
Try
{Calculator c=(Calculator)
Naming.looup(
“rmi://localhost/CalculatorService”);
System.out.println(c.sub(4,3));
System.out.println(c.add(4,5));
System.out.println(c.sub(3,6));
System.out.println(c.sub(9,3));
}
Catch(MalformedURLException murle)
{
System.out.println();
System.out.println(“MalformedURLException”);
System.out.println(murle);
}
Catch(RemoteException re)
{System.out.println();
System.out.println(“RemoteException”);
System.out.println(re);
}
IT E74 WEB TECHNOLOGY
Department Of Information Technology 19
Catch(NotBoundException nbe)
{System.out.println();
System.out.println(“NotBoundException”);
System.out.println(nbe);
}
Catch(java.lang.ArithmeticException ae)
{System.out.println();
System.out.println(“java.lang.ArithmeticException”);
System.out.println(ae);
}}}
4.server side
The server program should register at least one remote object with the object registry. The statement for the is Naming.rebind{
objectName,object);
Import java.rmi.Naming;
Public calss CalculatorServer{
Public CalculatorServer()
{
Try
{
Calculator c= new CalculatorImpl();
Naming.rebind(“rmi://localhost:6060/calculatorService”,c);
}
Catch(Exception e)
{
System.out.println(“trouble:”+e);
}
}
Public static void main(String arg[])
New CalculatorServer();
}
}
5.Running the program:
Before starting the server, start the object registry, using the command
Rmiregistry &
The server should then be started using the command
Java helloserver &
The server will take a few seconds to start running and to construct and register remote object. The client is run like any
other object.th example client is executed using
Java calculator client
IT E74 WEB TECHNOLOGY
Department Of Information Technology 20
Protocol handler
Most popular web browser support protocol other than HTTP .these other protocols include FTP ,gopher ,email and
application specification protocols .support for these protocols are built into browse rto became larger and slower to load
Java support additional protocol through the use of protocol handle referred to us the stream handler .these protocol handler
are used to retrieve web objects using application specific protocol. The protocol are specified in the URL referring the objects
Protocol handlers are implemented as subclasses of thr URLS team handler class. The URLStreamhandler classs defines
four accessmethod that can be overridden by its subclasses,but only the openconnection() method is required to be overridden
The openconnection() method tokes a URL with its assigned protocol as a parameter and return an object of class
URLconnection .the URLconnection object can be used to create input and output streams and to access the resource addressed by
the URL
The parseURL() and set URL() method are used to implement custom URL syntax parsing.the to ExternalForm() method is
used to convert the URL of the protocol type to a string object
The purpose of a protocol handler is used to implement a customer protocol needed to access web object identified URLs
that requires the custom protocol. Protocol handlers, are not directly installatatiated are accessed . the method of the
URLconnections object that‟s is returned by a protocol handler are invoked to access the resource referenced by the protocol
A protocol is indentified beginning with the first character of the URL and continuing to the first colon (:) contain the URL
.for example the protocol of the URL http://www.myportal.com/ is http and the protocol of the URLmyprotocol//myweb.com is my
protocol
4.6. Developing a protocol handler
The first step to implement a protocol handler is to defined the protocol handler as sub class of the URLstreamhandler class
.the open connection method of the protocol handler creates an URL connection object that can be used to acess an URL
designating the specified protocol
A protocol handler is associated with a specific protocol type through the use of a URLStreamHandlerFactory object.the
create URLstreamHandlerFactory interface is used to return a protocol handler for a specific protocol type
The set URLStreamHandlerFactory() method of the URL class is used to set an URLStreamFactory as the default
URLStreamhandlerfactory as the defaultURLStreamhandlerfactory to be used all protocol types
4.6.1. a simple protocol handler
Following is an example of implementing a simple protocol handler. In the example there is a CGI program ,named
myprotocol, that‟s returns a cookie type message when the URL of the program is access this section defines the myprotocol to
access the myprotocol program on the web server the protocol is a not a real internet protocol;
It is an example to illustrate the use of protocol handlers .the URL for the example is protocol consisting of myprotcol://
followed by hostname.for example, myprotocol://myportal.com access the illustrate protocol on the web server
the definition of the URL illustratehandler class is shown
import java.net.*;
import java.io.*;
public class URLillustraehandler extends URLstreamhandler
{
Public URLConnectio openconnection(URL url) throws
IOException
{
String host=url.gethost();
URL newURL = new URL (http://”+host+”/cgi-bin/myprotocol”);
Return newURL.openconntection();
}}
The URLillustraehandler class extends the URLstream handler class and provide a single method that is the
openconnection() method which takes a URL object as a parameter and returns an object of the URL connection the class.it also
throw the IOException
IT E74 WEB TECHNOLOGY
Department Of Information Technology 21
The openconnectio() method uses gethost() method of the URL class to extact the host name conatinig the URL . it then ,uss the
http URL by contain http ://with the host name and then the location of th my protocol CGI program, /CGI-bin/myprotocl .the
openconnection() method of the URL class is used too return the URLconnection object associated with new URL
The URLillustredhandler class wraps the myprotocol CGI program using the myprotocol protocol .thirds protocol is
implemented through an HTTP connection to CGI program
The getapplication program illustrate the use of protocolhandler . it access the myprotocol program on the web server using the
example protocol
Import java.net.*;
Import java.io.*;
Public class getapplication
{
Public static void main (string arg[])
{
Try{
illustratefactory illustratefactory =new illustratefactory ();
URL.setURLStreamhandlerfactory(illustratefactory);
If (arg.length!=1) error (“usage;getillustrateapplication illustrateURL”);
System.out.println(“fetching URL:”+args[0]);
URL url=new URL(args[0]);
System.out.println((string) url.getcontent());
}catch(malformedURLexception ex)
{
Error(“bad URL”);
}catch(IOException ex)
{
Error(“IOException occurred.”);
}
}
Public static void error( string s){
System.out.println(s );
System.exit(1);}}
Class illustreatfactory implements URLstreamhandlerfactory{
Public illustratefactory()
{
}
Public URLstreamhandler creatURLstreamhandler(string protocol){
If(protocol.equals(“myporotocol))
{
System.out.println(“requeted protocol:”+protocol);
Return new URLillustredhandler();
}
Return null; }}
IT E74 WEB TECHNOLOGY
Department Of Information Technology 22
4.7.Content handlers
A web browser encounters the number of external programs are plug in that are used to supplement the capabilities provide
by the browser. These external programs are used to display and process file that sre not normally supported by the browser
Java support additional internal of external program to the cntent handler mechanism .conthen handler are used to retrieve
object via a URL connection object
Content handler are implemented as subclass of the contenthandler class .a content handler is only required a to implement
the single method the getcontent() method that override the method provided by the contend handler class this method takes an
URLconnection object as a parameter an d returns an object of an specific MIME ( multipurpose internet mail extension) type
The purpose of ta contenthandler is to extract an object of a given MIME type from the input stream of a URLconnection
object.content handlerare not directly instated or accessed. The getcontent() method of th URL and URLconnection classes cause
handler to be created to invoked to perform their processing
4.7.1.Developing a content handler
The first step to implementing the content handler idsto define the class of the object to extracted the content handler. The
contend handler is the define as subclass of the contenhandler class .the getconten() method of the content handler perform the
extraction of the object of a specific MIME type from the input stream associated with the URL connection object
A content handler is associate dwith the MIME type the through use of the contenthandlerfactory object .the create
contenthandler() method of the contenthandlerfactory interface is used to return a content handler for a specific MIME type
Finally ,the setcontenthandlerfactory() method of the URLconnectino calss used to setcontenhandler() as the default content
handlerfactory to be with all MIME types
4.7.2 Simple content handler
An example of implementing a simple content handler is explained below an example MIME type a.text/cg,is created to
implement object of the character grid type .it uses the O character to draw the grid . the grid is specified by the Boolean array theta
identifies whether the drawing character is to displayed. This particular character grid is represented using the following text string :
55010010101001000101010001
The first character(5) represent the grid height .the second character also (5) represent the grid with. The third character is
the grid drawing character. The renaming character specific whetted the draw character to be displayed at a particular grid position
.one signified that the draw character should be displayed and 0 sgininfec that it should not be displayed. The array is arranged in
row order beginning with to pm of the grid
Public class chargrid
{
Public int height;
Public int width;
Public char ch;
Public Boolean value[][];
Public chargrid(int h int w char c,Boolean value[][])
{ height=h;
Width=w;
Ch=c;
Value=val;
}}
3.8.3 the gridcontenthandler class
The gridcontenthandler class is used to extract chargrid object from an URLconnection
Import java.net.*;
Import java.io.*;
Public class gridcontenthandler extends contenthandler{
Public object getcontent(URLconnection url) thrown
IT E74 WEB TECHNOLOGY
Department Of Information Technology 23
IOException{
Datainputstream in =new
Datainputstream(url.getinputstream());
Int height=(int) in.readbyte()-48;
Int width=(int) in.readbyte()-48;
Char ch=(char) in.readbyte();
Boolean values[][]=new boolean[height][width];
For(int i=0;i<height;++i)
{
For(int j=0;j>width;++j)
{
byte b= in.readbyte()
if(b==48) value[i][j]=true;
}}
In.close();
Return new chargrid(height,width,ch);
}}
The gridcontenthandeler class extends the contenthandler class and provide the single method.the getcontent() method takes
an URLconnecton object as an parameter and returns an object of an object class it also throws the IOException exception
The getcontent() method creates an object of class datainpustream and assign it to the variable it uses getinputstream()
method of the URLconnection class to access the inputstream associated with a URLconnection
3.8.4 the getgridapplication program
The getgridapplication illustrate the use of content handlers.it retives an object of the chargrid type from he web server
Import java.net.*;
Import java.io.*;
Public class getgridapplication{
Public static void main(string args[]){
Try{
Gridfactory Gridfactory=new Gridfactory();
URLconnection.setcontenthandlerfactory(Gridfactory);
If(args.lenght!=1) error(“usage:java getgridAPP URL”);
System.out.prinln(“fetchinf URL:”+args[o]);
URL url=new URL(args[0]);
Char grid cg=(chargrid URL.getconten());
System.out.prinln(“height:”cg.height);
System.out.prinln(“width:”cg.width);
system.out.prinln(“char:”cg.ch);
for (int i=0;i<cg.height;++i)
{
For(intj=0;j<cg.width;++j){
If(cg.value[i][j]) System.out.prinl(cg.ch);
IT E74 WEB TECHNOLOGY
Department Of Information Technology 24
else System.out.print(“ ”);
} System.out.print();
}}catch(malform URLException ex)
{
Error(“bad URL”);
}catch(IOException ex)
{
Error(“IOException occurred.”);
}
}
Public static void error( string s){
System.out.println(s );
System.exit(1);
}
}class gridfactory implement contenhandlerfactory{
Public gridfactory (){
}
Public contenthacndle creatcontenthandlder(string mime type)
If(mime type.equal(“text /cg))
{
System.out.println(“requeste mime type:”+mime type );
Return new gridcontenthandler();
}return null;
}
}
The getgridapp program defines the gridfactory as a contenthandlerfactory.it implements the create contenthandler() method
and checks to see if the MIME typr passed to it is text cg. if it is not, the null value is return to the single that the java supply
content handler should be used. If the MIME type ids text /cg,the requested the MIME types displayed d and the gridcontenthandler
object is returned