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

Module 7 Networking and RMI Updated

Uploaded by

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

Module 7 Networking and RMI Updated

Uploaded by

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

Network Programming

PMCA502L: Thilagavathi M, AP(Sr.), SITE


java.net Package
• Classes
 InetAddress
 Socket
 ServerSocket
 DatagramPacket
 DatagramSocket

PMCA502L: Thilagavathi M, AP(Sr.), SITE


InetAddress Class

PMCA502L: Thilagavathi M, AP(Sr.), SITE


InetAddress Class
Instance Methods
• getAddress()
• getHostAddress()
• getHostName()
• hashCode()
• isMulticastAddress()
• isReachable(int timeout)
• toString()

PMCA502L: Thilagavathi M, AP(Sr.), SITE


InetAddress Instance Methods

PMCA502L: Thilagavathi M, AP(Sr.), SITE


InetAddress Class

PMCA502L: Thilagavathi M, AP(Sr.), SITE


TCP/IP Socket Class
• Constructors
Socket( )
Socket(String hostName, int port)
Socket(InetAddress addr, int port)
• Methods
InetAddress getInetAddress( )
int getPort( )
int getLocalPort()
InputStream getInputStream( )
OutputStream getOutputStream( )
void close( )
boolean isClosed( )
boolean isConnected( )
PMCA502L: Thilagavathi M, AP(Sr.), SITE
TCP/IP ServerSocket Class
• Constructor
ServerSocket(int port)
ServerSocket(int port, int maxQueue)
• Method
Socket accept( )

PMCA502L: Thilagavathi M, AP(Sr.), SITE


PMCA502L: Thilagavathi M, AP(Sr.), SITE
PMCA502L: Thilagavathi M, AP(Sr.), SITE
Example

PMCA502L: Thilagavathi M, AP(Sr.), SITE


PMCA502L: Thilagavathi M, AP(Sr.), SITE
A client-server program to exchange a
message.
// Client program
import java.net.*;
import java.io.*;
public class fclient{
public static void main(String args[]) {
try {
Socket s = new Socket ("localhost",5000);
System.out.println("Connection established.........");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String str = br.readLine();
OutputStream os = s.getOutputStream();
PrintStream ps = new PrintStream(os);
ps.println(str);
System.out.println("Message Sent");
InputStream is = s.getInputStream();
InputStreamReader isr1 = new InputStreamReader(is);
BufferedReader br1 = new BufferedReader(isr1);
String str1 = br1.readLine();
System.out.println("Message Reveived");
System.out.println("server Message is " +str1);
}
catch(Exception e) { System.err.println(e); }
}
} PMCA502L: Thilagavathi M, AP(Sr.), SITE
A client-server program to exchange a
message.
//server program
import java.net.*;
import java.io.*;
public class fserver {
public static void main(String args[ ]) {
try {
ServerSocket ss = new ServerSocket(5000);
Socket s = ss.accept( );
InputStream is = s.getInputStream( );
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = br.readLine( );
System.out.println("Message Received");
System.out.println("Client Message is" +str);
OutputStream os = s.getOutputStream( );
PrintStream ps = new PrintStream(os);
ps.println("Message Received");
System.out.println("Message sent");
s.close( );
ss.close( );
}
catch(Exception e) {
System.out.println(e);
}
}
PMCA502L: Thilagavathi M, AP(Sr.), SITE
Datagrams
• Java implements datagrams on top of
UDP protocol using two classes
 DatagramSocket
 DatagramPacket

PMCA502L: Thilagavathi M, AP(Sr.), SITE


DatagramSocket

• It represents a connection-less socket for sending


and receiving datagram packets.
• A DatagramSocket can send to multiple, different
addresses.
• The address to which data goes is stored in the
packet, not in the socket.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


DatagramSocket
• Constructors
 public DatagramSocket() throws
SocketException
 public DatagramSocket(int port) throws
SocketException
 public DatagramSocket(int port, InetAddress
addr) throws SocketException
• Methods
 receive(DatagramPacket)
 send(DatagramPacket)

PMCA502L: Thilagavathi M, AP(Sr.), SITE


DatagramPacket
• It represents a message that can be sent or received. If
you send multiple packets, they may arrive in any order.
Also, packet delivery is not guaranteed.
• Constructors
 DatagramPacket(byte[] barr, int length) //to receive
 DatagramPacket(byte[] barr, int length, InetAddress
address, int port) //to send
• Methods
 InetAddress getAddress()
 int getPort()
 byte[] getData()
 int getLength()

PMCA502L: Thilagavathi M, AP(Sr.), SITE


Example

PMCA502L: Thilagavathi M, AP(Sr.), SITE


Example

PMCA502L: Thilagavathi M, AP(Sr.), SITE


Remote Method Invocation
• RMI (Remote Method Invocation) is an API that provides
a mechanism by which an object can invoke methods on
another object running in a different JVM.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


Overview of RMI
• Java RMI allowed programmer to execute
remote function class using the same
semantics as local functions calls.

Local Machine (Client) Remote Machine (Server)

SampleServer remoteObject;
int s;

s = remoteObject.sum(5);
5
public int findsum(int n) {
int sum=0;

System.out.println(s);
15 for(int
i=1;i<=n;i++)
sum+=i;
return sum;

}
The General RMI Architecture
Remote Machine
• The server must first bind
its name to the registry bind
RMI Server
• The client lookup the
server name in the Registry

registry to establish skeleton

remote references.
• The Stub serializing the return call lookup
parameters to skeleton,
the skeleton invoking the
remote method and stub

serializing the result back


to the stub. RMI Client

Local Machine
Architecture

Client Server

Stubs Skeletons

Transport
The Stub and Skeleton
call

skeleton
Stub
RMI Client RMI Server
return

• A client invokes a remote method, the call is first


forwarded to stub.
• The stub is responsible for sending the remote call
over to the server-side skeleton
• The stub opening a socket to the remote server,
marshaling the object parameters and forwarding the
data stream to the skeleton.
• A skeleton contains a method that receives the remote
calls, unmarshals the parameters, and invokes the
actual remote object implementation.
Remote Method Invocation
• Steps:
 RMI server program creates some remote objects. Objects
with methods that can be invoked across Java virtual
machines are called remote objects.
 makes references to these objects accessible by either
registering its remote objects with RMI's simple naming
facility, the RMI registry or by passing and returning
remote object references as part of other remote
invocations.
 Then it waits for clients to invoke methods on these
objects.
 A client program obtains a remote reference to one or
more remote objects on a server and then invokes
methods on them.
• Details of communication between remote objects are handled
by RMI. To the programmer, remote communication looks
similar to regular Java method invocations.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

• Let’s define two methods findFactorial() and findSum()


as remote methods which will be invoked by the client to
display the factorial of a number and sum of ‘n’ natural
numbers.
• Following are the 4 files to be created for this
application.
 Number.java, NumberImplementation.java,
NumberClient.java and NumberServer.java

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Number.java
• How can an object be designated as a Remote object?
 A method is defined as a remote method, by
declaring it in an interface which extends 'Remote'
interface.
 Each method of the interface should throw
RemoteException, in addition to any application-
specific exceptions.
 The interface 'Remote' and the class
'RemoteException' are defined in java.rmi package.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Number.java

import java.rmi.*;
public interface Number extends Remote {
public int findFactorial(int n) throws RemoteException;
public int findSum(int n) throws RemoteException;
}

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

NumberImplementation.java
• Next, implement the interface to help create remote
objects.
• The class should not only implement the interface but
also extend UnicastRemoteObject.
 A remote method may accept arguments of primitive
data types or objects. To send and receive objects,
serialization and deserialization of objects are
essential. If the class is defined to be extended from
UnicastRemoteObject, serialization of the objects will
be done automatically.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

NumberImplementation.java
import java.rmi.*;
import java.io.*;
import java.rmi.server.UnicastRemoteObject;
public class NumberImplementation extends UnicastRemoteObject
implements Number
{
public NumberImplementation() throws RemoteException {
super();
}
public int findFactorial(int n) throws RemoteException {
int fact=1;
for(int i=1;i<=n;i++)
fact*=i;
return fact;
}
PMCA502L: Thilagavathi M, AP(Sr.), SITE
RMI – Working with a Sample Application

public int findSum(int n) throws RemoteException {


int sum=0;
for(int i=1;i<=n;i++)
sum+=i;
return sum;
}

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Naming Class
• Naming class provides methods for storing and obtaining references
to remote objects in a remote object registry.
• A remote object can be associated with a name using the Naming
class's bind or rebind methods.
• Once a remote object is registered (bound) with the RMI registry on
the local host, callers on a remote (or local) host can lookup the
remote object by name, obtain its reference, and then invoke
remote methods on the object.
• Methods
 static void bind(String name, Remote obj)
throws AlreadyBoundException
 static void rebind(String name, Remote obj)
 static void unbind(String name) throws NotBoundException
 static Remote lookup(String name)

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

NumberServer.java
import java.rmi.*;
import java.io.*;
public class NumberServer {
public static void main(String[] args) {
try{
NumberImplementation ni=new NumberImplementation();
Naming.rebind("rmi://localhost//NumServer",ni);
//NumServer is the name bound to the object - ni
}
catch(Exception e) {
e.printStackTrace();
}
}
}

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

NumberClient.java
import java.rmi.*; import java.util.Scanner;
public class NumberClient {
public static void main(String[] args) {
try {
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
Number n1 =
(Number)Naming.lookup("rmi://localhost//NumServer");
System.out.println("Factorial is: "+n1.findFactorial(n));
System.out.println("Sum of n Numbers is: "+n1.findSum(n));
}
catch(Exception e) { e.printStackTrace(); }
}
}

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Starting the Application


• Use the javac compiler to compile the 4 source files.
• Before starting the compute engine, RMI registry needs to be
started and to start it on the server, the rmiregistry command
should be executed. If your server is on a Windows machine the
command is:
start rmiregistry
• Invoke rmi compiler to generate stubs and skeletons using the
command
rmic NumberImplementation
 Stub: Stub is a gateway for client program which is used to communicate with
skeleton object, by establishing a connection between them.
 Skeleton: Resides on Server program which is used for passing the request from
stub to the remote interface.
• Now execute NumberServer.java and NumberClient.java

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Use the javac compiler to compile the 4 source files.

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Start the rmi registry using the following command


start rmiregistry

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Invoke rmi compiler to generate stubs and skeletons using the


command
rmic NumberImplementation

PMCA502L: Thilagavathi M, AP(Sr.), SITE


RMI – Working with a Sample Application

Finally execute NumberServer.java first and then NumberClient.java

PMCA502L: Thilagavathi M, AP(Sr.), SITE

You might also like