0% found this document useful (0 votes)
2 views43 pages

Chapter 2 Networking in Java

Chapter 2 discusses networking in Java, covering concepts such as network programming, socket communication, and the use of protocols like TCP and UDP. It explains the Java InetAddress class for handling IP addresses and domain names, as well as the implementation of client and server sockets for data exchange. Additionally, it introduces DatagramSocket and DatagramPacket for connectionless communication and Remote Method Invocation (RMI) for distributed applications.

Uploaded by

amanuelgurara55
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views43 pages

Chapter 2 Networking in Java

Chapter 2 discusses networking in Java, covering concepts such as network programming, socket communication, and the use of protocols like TCP and UDP. It explains the Java InetAddress class for handling IP addresses and domain names, as well as the implementation of client and server sockets for data exchange. Additionally, it introduces DatagramSocket and DatagramPacket for connectionless communication and Remote Method Invocation (RMI) for distributed applications.

Uploaded by

amanuelgurara55
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 2

Networking in Java
1
[Link] Programming
•Network: a group of computers connected
with each other via some medium and
transfer data between them as and when
require.
•Java supports Network Programming so we
can make such program in which the
machines connected in network will send and
receive data from other machine in the
network by programming.
➢Java Networking is a concept of connecting two
or more computing devices together so that we
can share resources. 2
Network Programming
•The first and simple logic to send or receive
any kind of data or message is we must
have the address of receiver or sender.
• So when a computer needs to communicate with
another computer, it`s require the other
computer’s address.
•Java networking programming supports
the concept of socket.
• A socket identifies an endpoint in a network.
• The socket communication takes place via a
protocol.

3
Network Programming
• The Internet Protocol is a lower-level, connection
less (means there is no continuing connection
between the end points) protocol for delivering the
data into small packets from one computer
(address) to another computer (address) across
the network (Internet).
• It does not guarantee to deliver sent packets to the
destination.
• The most widely use a version of IP today is IPv4,
uses a 32 bit value to represent an address which
are organized into four 8-bits chunks.
• However new addressing scheme called IPv6, uses a
128 bit value to represent an address which are
organized into four 16-bits chunks. 4
Network Programming
•The main advantage of IPv6 is that it supports
much larger address space than does IPv4.
•An IP address uniquely identifies the computer
on the network.
•IP addresses are written in a notation using
numbers separated by dots is called dotted-
decimal notation.
•There are four 8 bits value between 0 and 255
are available in each IP address such as
[Link] means local- host, [Link] etc
5
Network Programming
• It`s not an easy to remember because of so many
numbers, they are often mapped to meaningful
names called domain names such as [Link]
• There is a server on Internet who is translate the host
names into IP addresses is called DNS (Domain Name
Server).
• When a user pass the URL like [Link] in the
web-browser from any computer, it first ask to DNS to
translate this domain name into the numeric IP
address and then sends the request to this IP
address.
• This enables users to work with domain names, but
the internet operates on IP addresses.
6
Network Programming
• The Higher-level protocol used in with the IP are TCP and
UDP.
• The TCP enables two host to make a connection and exchange
the stream of data, so it`s called Stream-based
communication.
• TCP guarantees delivery of data and also guarantees that
streams of data will be delivered in the same order in which
they are sent.
• The TCP can detect the lost of transmission and so resubmit
them and hence the transmissions are lossless and reliable.
• The UDP is a standard, directly to support fast, connectionless
host- to-host datagram oriented model that is used over the IP
and exchange the packet of data so it`s called packet-based
communication.
• The UDP cannot guarantee lossless transmission.
• JAVA supports both TCP and UDP protocol families.
7
Java InetAddress Class
• Java InetAddress Class is used to encapsulate the two
thing.
1. Numeric IP Address
2. The domain name for that address.
• The InetAddress can handle both IPv4 and IPv6 addresses.
• It has no visible constructors so to create its object, the user
have to use one of the available in-built static methods.
• The commonly used InetAddress in-built methods are:
• 1. getLocalHost(): It returns the InetAddress object that
represents the local host contain the name and address both.
• If this method unable to find out the host name, it throw an
UnknownHostException.
• Syntax:
Static InetAddress getLocalHost() throws UnknownHostException
8
Cont’d
• 2. getByName(): It returns an InetAddress for a host
name passed to it as a parameter argument.
• If this method unable to find out the host name, it throw an
UnknownHostException.
• Syntax:
Static InetAddress getByName(String host_name) throws
UnknownHostException
• 3. getAllByName(): It returns an array of an
InetAddress that represent all of the addresses that a
particular name resolve to it.
• If this method can’t find out the name to at least one address,
it throw an UnknownHostException.
• Syntax:
Static InetAddress[] getAllByName(String host_name) throws
UnknownHostException 9
Program: Write down a program which demonstrate an InetAddress class.
import [Link];
import [Link];
public class InetAddress_Demo {
public static void main(String[] args) {
String name = "";
try {
[Link]("HOST NAME - Numeric Address :
"+[Link]());
InetAddress ip = [Link](name);
[Link]("HOST DEFAULT-NAME / IP :"+ip);
[Link]("HOST IP-ADDRESS : "+[Link]());
[Link]("HOST DEFAULT-NAME : "+[Link]());
} catch (UnknownHostException e) {
[Link]("Coudn't find the IP-ADDRESS for :"+name);
}
} } 10
Socket Programming
• Java network Programming supports the concept of
socket.
• A socket identifies an endpoint in a network.
• The socket communication take place via a protocol.
• A socket can be used to connect JAVA Input/Output
system to other programs that may resides either on
any machine on the Internet or on the local
machine.

11
Socket Programing in Java

12
Socket Programming
• TCP/IP Sockets:
• TCP/IP sockets are used to implement point-to-
point, reliable, bidirectional, stream-based
connections between hosts on the Internet.
• There are two types of TCP sockets available in
java:
1. TCP/IP Client Socket
2. TCP/IP Server Socket

13
1. TCP/IP Client Socket
• The Socket class (available in [Link] package) is for the
Client Socket.
• It is designed to connect to server sockets and initiate
protocol exchange.
• There are two constructers used to create client sockets
type object.
a. Socket(String host_name, int port) throws UnknownHostException,
IOException
➢it creates a socket that is connected to the given host_name and port
number.
b. Socket(InetAddress ip, int port) throws IOException
➢ it creates a socket using a pre-existing InetAddress object and a port
number.

14
2. TCP/IP Server Socket
• The ServerSocket class (available in [Link] package)
is for the Server.
• It is designed to be a “listener”, which waits for clients
to connect before doing anything and that listen for
either local or remote client programs to connect to
them on given port.
• When you create ServerSocket it will register itself
with the system as having an interest in client
connection.
• Syntax:
ServerSocket(int port) throws IOException

15
Program: Write down a program which demonstrate the Socket
programming for passing the message from server to client.
//[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Client {
public static void main(String[] args) {
[Link]("Sending a request.....");
try {
Socket s = new Socket("[Link]",1564);
16
[Link]("connected successfully.....");
BufferedReader br = new BufferedReader(new

InputStreamReader([Link]()));
[Link]("response from server...");
[Link]("Client side : "+[Link]());
[Link]();
} catch (UnknownHostException e) {
[Link]("Not find the IP-ADDRESS for :"+e);
} catch (IOException e) {
[Link]("Not Found data for Socket : "+e);
}
}
}

17
//[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(1564);
[Link]("waiting for request....");
Socket s = [Link]();
[Link]("Request accepted");
18
PrintStream ps = new PrintStream([Link]());
BufferedReader br = new BufferedReader(new

InputStreamReader([Link]));
[Link]("Input the data at server : ");
[Link]([Link]());
[Link]();
[Link]();
} catch (Exception e) {
[Link]("Not Found data for Socket : "+e);
}
}
}
19
2.2. DatagramSocket and DatagramPacket
• Is a Sockets that use UDP for transport of packets.
• Java DatagramSocket and DatagramPacket classes are
used for connection-less socket programming using the
UDP instead of TCP.
• Datagram
▪Datagrams are collection of information sent from one device
to another device via the established network.
▪When the datagram is sent to the targeted device, there is no
assurance that it will reach to the target device safely and
completely.
▪It may get damaged or lost in between. Likewise, the
receiving device also never know if the datagram received is
damaged or not.
▪The UDP protocol is used to implement the datagrams in
Java. 20
2.2. DatagramSocket and DatagramPacket
• In Java, two classes are provided for the datagram socket API:-
a) The DatagramSocket class for the sockets
b) The DatagramPacket class for the packets exchanged.
• A process wishing to send or receive data using the datagram
socket API must instantiate a DatagramSocket object, which is
bound to a UDP port of the machine and local to the process.
• To send a datagram to another process, the sender process must
instantiate a DatagramPacket object that carries the following
information:
• (1) a reference to a byte array that contains the payload data
and
• (2) the destination address (the host ID and port number to
which the receiver process’ DatagramSocket object is bound).

21
2.2. DatagramSocket and DatagramPacket
• At the receiving process, a DatagramSocket object must be
instantiated and bound to a local port – this port should
correspond to the port number carried in the datagram packet of
themsender.
• To receive datagrams sent to the socket, the receiving process
must instantiate a DatagramPacket object that references a byte
array and call the receive method of the DatagramSocket object,
specifying as argument, a reference to the DatagramPacket
object.

22
2.2. DatagramSocket and DatagramPacket
• Program flow in the sender and receiver process
• Sender Program • Receiver Program
• Create a DatagramSocket ✓Create a DatagramSocket
objectand bind it to any local object and bind it to a
port; specific local port;
• Place the data to send in a ✓Create a byte array for
byte array; receiving the data;
• Create a DatagramPacket
object, specifying the data
✓Create a DatagramPacket
array and the receiver’s object, specifying the data
address; array.
• Invoke the send method of ✓Invoke the receive method
theDatagramSocket object and of the socket with a
pass as argument, a reference reference to the
to the DatagramPacket object. DatagramPacket object.
23
2.2. DatagramSocket and DatagramPacket
• DatagramSocket class
No. Constructor/ Method Description

24
2.2. DatagramSocket and DatagramPacket
• DatagramPacket class
No. Constructor/ Method Description

25
Example Program to Send and Receive a Message using
Connectionless Sockets ([Link] )
• import [Link].*;
• import [Link].*;
• class datagramReceiver{
• public static void main(String[ ] args){
• try {
• int MAX_LEN = 40;
• int localPortNum = [Link](args[0]);
• DatagramSocket mySocket = new DatagramSocket(localPortNum);
• byte[] buffer = new byte[MAX_LEN];
• DatagramPacket packet = new DatagramPacket(buffer, MAX_LEN);
• [Link](packet);
• String message = new String(buffer);
• [Link](message);
• [Link]( ); }
• catch(Exception e){[Link]( ); } } } 26
Example Program to Send and Receive a Message using
Connectionless Sockets ([Link] )
• import [Link].*;
• import [Link].*;
• class datagramSender{
• public static void main(String[ ] args) {
• try{
• InetAddress receiverHost = [Link](args[0]);
• int receiverPort = [Link](args[1]);
• String message = args[2];
• DatagramSocket mySocket = new DatagramSocket( );
• byte[] buffer = [Link]( );
• DatagramPacket packet = new DatagramPacket(buffer, [Link],
receiverHost, receiverPort);
• [Link](packet);
• [Link]( ); }
catch(Exception e) {
• [Link]( ); } } } 27
2.2. Remote Method Invocation (RMI)
• RMI is an API that provides a mechanism to create
distributed application in java.
• It allows an object to invoke methods on an object running
in another JVM.
• RMI provides remote communication between the
applications using two objects stub and skeleton.
• RMI uses stub and skeleton object for communication
with the remote object.
• A remote object is an object whose method can be
invoked from

28
2.3. Remote Method Invocation (RMI)
•stub
• The stub is an object, acts as a gateway for the client side.
• All the outgoing requests are routed through it.
• It resides at the client side and represents the remote object.
• When the caller invokes method on the stub object, it does the
following tasks:
a) It initiates a connection with remote Virtual Machine (JVM),
b) It writes and transmits (marshals) the parameters to the remote Virtual
Machine (JVM),
c) It waits for the result
d) It reads (unmarshals) the return value or exception, and
e) It finally, returns the value to the caller.

29
2.3. Remote Method Invocation (RMI)
•skeleton
• The skeleton is an object, acts as a gateway for the server side object.
• All the incoming requests are routed through it.
• When the skeleton receives the incoming request, it does the following
tasks:
a) It reads the parameter for the remote method
b) It invokes the method on the actual remote object, and
c) It writes and transmits (marshals) the result to the caller.

30
Requirements for the Distributed
Applications
•If any application performs these tasks, it can be
distributed application.
a)The application need to locate the remote
method
b)It need to provide the communication with
the remote objects, and
c)The application need to load the class
definitions for the objects.
•The RMI application have all these features, so it
is called the distributed application.
31
Java RMI Example

•Six(6) steps to write the RMI program.


a) Create the remote interface
b) Provide the implementation of the remote interface
c) Compile the implementation class and create the stub
and skeleton objects using the rmic tool
d) Start the registry service by rmiregistry tool
e) Create and start the remote application
f) Create and start the client application
32
RMI Example
• we have followed all the 6 steps to create and run the rmi application.
• The client application need only two files, remote interface and client
application.
• In the rmi application, both client and server interacts with the remote
interface.
• The client application invokes methods on the proxy object, RMI sends the
request to the remote JVM.
• The return value is sent back to the proxy object and then to the client application.

33
RMI Example
• 1) create the remote interface

• For creating the remote interface, extend the Remote


interface and declare the RemoteException with all the
methods of the remote interface.
• Here, we are creating a remote interface that extends
the Remote interface.
[Link] [Link].*;
[Link] interface Adder extends Remote{
[Link] int add(int x,int y)throws RemoteException;
4.} 34
2) Provide the implementation of the
remote interface
• For the implementation of the Remote interface, we
need to
• Either extend the UnicastRemoteObject class, or use the
exportObject() method of the UnicastRemoteObject class.

[Link] [Link].*;
[Link] [Link].*;
[Link] class AdderRemote extends UnicastRemoteObject implements
Adder{
[Link]()throws RemoteException{
[Link]();
6.}
[Link] int add(int x,int y){return x+y;}
8.}
35
3) create the stub and skeleton objects
using the rmic tool.
• Next step is to create stub and skeleton objects
using the rmi compiler.
• The rmic tool invokes the RMI compiler and
creates stub and skeleton objects.
o rmic AdderRemote

36
4) Start the registry service by the
rmiregistry tool
• Now start the registry service by using the rmiregistry
tool.
• If you don't specify the port number, it uses a
default port number.
▪ In this example, we are using the port number 4000.
▪ rmiregistry 4000

37
5) Create and run the server
application(1)
• Now rmi services need to be hosted in a server
process.
• The Naming class provides methods to get and store
the remote object.
• The Naming class provides 5 methods.

38
5) Create and run the server
application(2)
public static [Link] lookup([Link]) It returns the reference of the
throws [Link], remote object.
[Link],
[Link];
public static void bind([Link], [Link]) It binds the remote object with
throws [Link], the given name.
[Link],
[Link];
public static void unbind([Link]) throws It destroys the remote object
[Link], [Link], which is bound with the given
[Link]; name.
public static void rebind([Link], It binds the remote object to the
[Link]) throws [Link], new name.
[Link];
public static [Link][] list([Link]) It returns an array of the names of
throws [Link], the remote objects bound in the
[Link]; registry. 39
Example of RriExampleServer class
▪import [Link].*;
▪import [Link].*;
▪public class RriExampleServer{
▪public static void main(String args[]){
▪try{
▪Adder stub=new AdderRemote();
▪[Link]("rmi://localhost:4000/user", stub)
▪}catch(Exception e)
▪{[Link](e);}
▪}
▪} 40
6) Create and run the client application
• At the client we are getting the stub object by the
lookup() method of the Naming class and invoking the
method on this object.
• In this example, we are running the server and client
applications, in the same machine so we are using localhost.
• If you want to access the remote object from another machine,
change the localhost to the host name (or IP address) where
the remote object is located.

41
Example of RriExampleClient
[Link] [Link].*;
[Link] class RriExampleClient{
[Link] static void main(String args[]){
[Link]{
[Link] stub=(Adder)[Link]("rmi://localhost:50
00/user");
[Link]([Link](34,4));
7.}catch(Exception e){}
8.}
9.}
42
For Meaningful RMI application use
database for two Remote devices,
• There are two applications running in different
machines. Let's say MachineA and MachineB,
machineA is located in X and MachineB in Y. MachineB
want to get list of all the students of MachineA
application.
• Develop the RMI application ,

43

You might also like