Network Programming
PMCA502L: Thilagavathi M, AP(Sr.), SITE
[Link] 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 [Link].*;
import [Link].*;
public class fclient{
public static void main(String args[]) {
try {
Socket s = new Socket ("localhost",5000);
[Link]("Connection established.........");
InputStreamReader isr = new InputStreamReader([Link]);
BufferedReader br = new BufferedReader(isr);
String str = [Link]();
OutputStream os = [Link]();
PrintStream ps = new PrintStream(os);
[Link](str);
[Link]("Message Sent");
InputStream is = [Link]();
InputStreamReader isr1 = new InputStreamReader(is);
BufferedReader br1 = new BufferedReader(isr1);
String str1 = [Link]();
[Link]("Message Reveived");
[Link]("server Message is " +str1);
}
catch(Exception e) { [Link](e); }
}
} PMCA502L: Thilagavathi M, AP(Sr.), SITE
A client-server program to exchange a
message.
//server program
import [Link].*;
import [Link].*;
public class fserver {
public static void main(String args[ ]) {
try {
ServerSocket ss = new ServerSocket(5000);
Socket s = [Link]( );
InputStream is = [Link]( );
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = [Link]( );
[Link]("Message Received");
[Link]("Client Message is" +str);
OutputStream os = [Link]( );
PrintStream ps = new PrintStream(os);
[Link]("Message Received");
[Link]("Message sent");
[Link]( );
[Link]( );
}
catch(Exception e) {
[Link](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 = [Link](5);
5
public int findsum(int n) {
int sum=0;
[Link](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.
[Link], [Link],
[Link] and [Link]
PMCA502L: Thilagavathi M, AP(Sr.), SITE
RMI – Working with a Sample Application
[Link]
• 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 [Link] package.
PMCA502L: Thilagavathi M, AP(Sr.), SITE
RMI – Working with a Sample Application
[Link]
import [Link].*;
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
[Link]
• 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
[Link]
import [Link].*;
import [Link].*;
import [Link];
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
[Link]
import [Link].*;
import [Link].*;
public class NumberServer {
public static void main(String[] args) {
try{
NumberImplementation ni=new NumberImplementation();
[Link]("rmi://localhost//NumServer",ni);
//NumServer is the name bound to the object - ni
}
catch(Exception e) {
[Link]();
}
}
}
PMCA502L: Thilagavathi M, AP(Sr.), SITE
RMI – Working with a Sample Application
[Link]
import [Link].*; import [Link];
public class NumberClient {
public static void main(String[] args) {
try {
Scanner sc=new Scanner([Link]);
[Link]("enter a number");
int n=[Link]();
Number n1 =
(Number)[Link]("rmi://localhost//NumServer");
[Link]("Factorial is: "+[Link](n));
[Link]("Sum of n Numbers is: "+[Link](n));
}
catch(Exception e) { [Link](); }
}
}
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 [Link] and [Link]
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 [Link] first and then [Link]
PMCA502L: Thilagavathi M, AP(Sr.), SITE