Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
46 views

Networking in Java

This document discusses networking concepts in Java, including sockets, TCP vs UDP, ports, and the InetAddress class. TCP provides a reliable connection-based protocol, while UDP sends independent datagrams without guarantees. Ports allow a single computer to distinguish between applications receiving data. The InetAddress class represents IP addresses and hostnames. Client-server applications typically use sockets for reliable communication, with the ServerSocket class handling server-side connections and the Socket class representing client connections.

Uploaded by

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

Networking in Java

This document discusses networking concepts in Java, including sockets, TCP vs UDP, ports, and the InetAddress class. TCP provides a reliable connection-based protocol, while UDP sends independent datagrams without guarantees. Ports allow a single computer to distinguish between applications receiving data. The InetAddress class represents IP addresses and hostnames. Client-server applications typically use sockets for reliable communication, with the ServerSocket class handling server-side connections and the Socket class representing client connections.

Uploaded by

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

NETWORKING IN JAVA

Sockets
 Computers running on the Internet communicate with each other using
either the Transmission Control Protocol (TCP) or the User Datagram
Protocol (UDP).
 When you write Java programs that communicate over the network, you
are programming at the application layer.
 Typically, you don't need to concern yourself with the TCP and UDP
layers.
 Instead, you can use the classes in the java.net package.
 These classes provide system-independent network communication.
 However, to decide which Java classes your programs should use, you do
need to understand how TCP and UDP differ.
Sockets…
 TCP is a connection-based protocol that provides a reliable flow of data
between two computers.
 When two applications want to communicate to each other reliably, they
establish a connection and send data back and forth over that connection.
 TCP guarantees that data sent from one end of the connection actually gets
to the other end and in the same order it was sent.
 Otherwise, an error is reported.
 HTTP, FTP, and Telnet are all examples of applications that require a
reliable communication channel.
 UDP is a protocol that sends independent packets of data, called
datagrams, with no guarantees about arrival.
 UDP is not connection-based unlike TCP.
 For many applications, the guarantee of reliability is critical to the success
of the transfer of information from one end of the connection to the other.
Sockets…
 However, other forms of communication don't require such strict standards.
 In fact, they may be slowed down by the extra overhead or the reliable
connection may invalidate the service altogether.

Ports
 Generally speaking, a computer has a single physical connection to the
network.
 All data destined for a particular computer arrives through that connection.
 However, the data may be intended for different applications/servers
running on the computer.
 So how does the computer know to which application to forward the data?
 Through the use of ports.
 Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it is
Sockets…
 The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network.
 Ports are identified by a 16-bit number, which TCP and UDP use to deliver
the data to the right application.

 In connection-based communication such as TCP, a server application binds a


socket to a specific port number.
 This has the effect of registering the server with the system to receive all data
destined for that port.
Sockets…
 Port numbers range from 0 to 65,535 because ports are represented by 16-
bit numbers.
 The port numbers ranging from 0 - 1023 are restricted.
 They are reserved for use by well-known services such as HTTP and FTP
and other system services.
 These ports are called well-known ports.
 Your applications should not attempt to bind to them.
InetAddress
 The InetAddress class is used to encapsulate both the numerical IP address
and the domain name of a computer.
 You interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address.
 The InetAddress class hides the number inside.
 InetAddress can handle both IPv4 and IPv6 addresses.
 The InetAddress class has no visible constructors and so to create an
InetAddress object, you have to use one of the available factory methods.
 Factory methods are merely a convention whereby static methods in a class
return an instance of that class.
 This is done instead of overloading a constructor with various parameter
lists when having unique method names makes the results much clearer.
 The static factory methods connect to a DNS server to resolve a hostname.
InetAddress…
 Three commonly used InetAddress factory methods are shown here:
 static InetAddress getLocalHost() - simply returns the InetAddress object that
represents the localhost.
 static InetAddress getByName(String hostName) throws UnknownHostException
– this returns an InetAddress for a host name passed to it. If these methods are
unable to resolve the host name, they throw an UnknownHostException.
 static InetAddress[ ] getAllByName(String hostName) throws
UnknownHostException - On the Internet, it is common for a single name to be
used to represent several machines. The getAllByName() factory method returns an
array of InetAddresses that represent all of the addresses that a particular name
resolves to.
 Throws an UnknownHostException if it can’t resolve the name to at least one
address.
 static InetAddress getByAddress(byte[] addr) – this returns an InetAddress object
given the raw IP address. The argument is in network byte order: the highest order
byte of the address is in index 0. IPv4 address byte array must be 4 bytes long and
IPv6 byte array must be 16 bytes long.
 static InetAddress getByAddress(String host, byte[] addr) - creates an InetAddress
InetAddress…
 The InetAddress class has several other methods, which can be used
on the objects returned by the methods discussed above.
 Here are some of the more commonly used methods:
Method Description
Returns a byte array that represents the object’s IP
byte[ ] getAddress()
address in network byte order.

Returns a string that represents the IP address associated


String getHostAddress()
with the InetAddress object.

Returns a string that represents the host name associated


String getHostName()
with the InetAddress object.
InetAddress…
 Example: creating InetAddress
class InetAddressTest {
public static void main(String args[]) throws UnknownHostException {
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.HerbSchildt.com");
System.out.println(address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
InetAddress…
 The bytes returned by getAddress() are unsigned, which poses a problem.
 Unlike C/C++, Java doesn’t have an unsigned byte primitive data type.
 Bytes with values higher than 127 are treated as negative numbers.
 Therefore, you need to promote the bytes to ints and make appropriate
adjustments.
 Here’s one way to do it:
int unsignedByte = signedByte < 0 ? signedByte + 256 : signedByte;
 Occasionally, you would like to know who is connecting to a server socket.
 You can use the InetAddress class to find the client’s host name and IP address.
 You can use the statement shown below in the server program to get an instance
of InetAddress on a socket that connects to the client.
InetAddress clientAddress = socket.getInetAddress();
 Next, you can display the client’s host name and IP address, as follows:
System.out.println("Client's host name is " + clientAddress.getHostName());
System.out.println("Client's IP Address is " + clientAddress.getHostAddress());
Sockets
 Most modern network programming is based on a client-server model.
 A client-server application typically stores large quantities of data on an expensive,
high-powered server while most of the program logic and the user interface is
handled by client software running on relatively cheap personal computers.
 In most cases, a server primarily sends data while a client primarily receives it; but
it is rare for one program to send or receive exclusively.
 A more reliable distinction is that a client initiates a conversation while a server
waits for clients to start conversations with it.
 By far, the most popular client-server system on the Internet is the Web(WWW).
 Web servers like Apache respond to requests from web clients like Firefox.
 Data is stored on the web server and is sent out to the clients that request it.
 Aside from the initial request for a page, almost all data is transferred from the
server to the client, not from the client to the server.
 FTP is an older service that fits the client-server model.
 People often use FTP to upload files from the client to the server, so it’s harder to
say that the data transfer is primarily in one direction, but it is still true that an FTP
client initiates the connection and the FTP server responds.
Sockets…
 In client-server applications, the server provides some service, such as
processing database queries or sending out current stock prices.
 The client uses the service provided by the server, either displaying database
query results to the user or making stock purchase recommendations to an
investor.
 The communication that occurs between the client and the server must be
reliable.
 That is, no data can be dropped and it must arrive on the client side in the same
order in which the server sent it.
 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.
 Java provides two classes, Socket and ServerSocket, that implement the client
side of the connection and the server side of the connection, respectively.
 A socket is bound to a port number so that the TCP layer can identify the
application that data is destined to be sent.
Sockets…
 Normally, a server runs on a specific computer and has a socket that is
bound to a specific port number.
 The server just waits, listening to the socket for a client to make a
connection request.
 On the client-side, the client knows the hostname of the machine on which
the server is running and the port number on which the server is listening.
 To make a connection request, the client tries to date with the server on the
server's machine and port.
 The client also needs to identify itself to the server so it binds to a local
port number that it will use during this connection.
 This is usually assigned by the system.
Sockets…
 If everything goes well, the server accepts the connection.
 Upon acceptance, the server gets a new socket bound to the same local port
and also has its remote endpoint set to the address and port of the client.
 It needs a new socket so that it can continue to listen to the original socket
for connection requests while tending to the needs of the connected client.

 On the client side, if the connection is accepted, a socket is successfully


created and the client can use the socket to communicate with the server.
 The client and server can now communicate by writing to or reading from
their sockets.
Sockets…
 The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program
and another program on the network.
 The Socket class sits on top of a platform-dependent implementation,
hiding the details of any particular system from your Java program.
 By using the java.net.Socket class instead of relying on native code, your
Java programs can communicate over the network in a platform-
independent fashion.
Sockets…
Types of Sockets
 There are two kinds of TCP sockets in Java.
 One is for servers, and

 the other is for clients

 The ServerSocket class is designed to be a “listener,” which waits for


clients to connect before doing anything.
 The Socket class is designed to connect to server sockets and initiate
protocol exchanges.
 The creation of a Socket object implicitly establishes a connection between
the client and server.
 Once the Socket object has been created, it can also be examined to gain
access to the input and output streams associated with it.
 The methods of socket can throw an IOException if the sockets have been
invalidated by a loss of connection on the network.
TCP Server Sockets
 Java provides a ServerSocket class that represents server sockets.
 The ServerSocket class is used to create a server that listens for client
programs to connect to it on published ports.
 A server socket runs on the server and listens for incoming TCP
connections.
 Each server socket listens on a particular port on the server machine.
 When a client on a remote host attempts to connect to that port, the server
negotiates the connection between the client and the server, and returns a
regular Socket object representing the socket between the two hosts.
 In other words, server sockets wait for connections from clients.
 Once a ServerSocket has set up the connection, the server uses a regular
Socket object to send data to the client.
 Data always travels over the regular socket.
 When you create a ServerSocket, it will register itself with the system as
having an interest in receiving client connections.
 The constructors for ServerSocket reflect the port number that you wish to
accept connections on and, optionally, how long you want the queue for
said port to be.
 The queue length tells the system how many client connections it can leave
pending before it should simply refuse connections.
 The default is 50.
 The constructors might throw an IOException under adverse conditions.
 Here are the constructors:
 ServerSocket(int port) - creates server socket on the specified port with

a queue length of 50 by default.


 ServerSocket(int port, int maxQueue) - creates a server socket on the

specified port with a maximum queue length of maxQueue.


 ServerSocket(int port, int maxQueue, InetAddress localAddress) -

creates a server socket on the specified port with a maximum queue


length of maxQueue. On a multihomed host, localAddress specifies the
IP address to which this socket binds.
TCP Server Sockets…
 Methods of ServerSocket
Methods description
InetAddress getInetAddress() It returns the local address occupied by the server socket.
int getLocalPort() It returns the local port occupied by the server socket.

boolean isBound() It returns the binding state of the ServerSocket. It returns true if the
ServerSocket has ever been bound to a port.
It listens for a connection to be made to this socket and accepts it. The
Socket accept() method blocks until a connection is made. It throws IOException if an
I/O error occurs when waiting for a connection.

boolean isClosed() Returns the closed state of the ServerSocket. It returns true if the socket
has been closed.
Closes this server socket. Any thread currently blocked in
void close() ServerSocket.accept() will throw a SocketException. It throws
IOException if an I/O error occurs when closing the socket.
Sets the default receive buffer size for sockets accepted by the server
setReceiveBufferSize(int size) socket. This controls the suggested send buffer size used for
network input.
int getReceiveBufferSize() Returns the value of the buffer size that will be used for Sockets
accepted from this ServerSocket.
TCP Server Sockets…
 Example: creating a server that listens for clients on port 4444
ServerSocket servSocket;
try {
servSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
 ServerSocket provides a system-independent implementation of the server
side of a client-server socket connection.
 The constructor for ServerSocket throws an exception if it can't listen on
the specified port (for example, the port is already being used).
 If the server successfully binds to its port, then the ServerSocket object is
successfully created and the server continues to accept a connection from a
 ServerSocket has a method called accept(), which is a blocking call that will
wait for a client to initiate connections
 It then return a normal Socket that is then used for communication with the
client.
 The accept() method returns a Socket object connecting the client and the
server.
 Example: accepting client request on the server after creating the listener
ServerSocket servSocket ;
Socket socket = null;
try {
servSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
try {
socket = servSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
TCP Server Sockets…
 Server manages each client connection with a Socket object.
 After binding the server to a port with a ServerSocket, the server listens
indefinitely (or blocks) for an attempt by a client to connect.
 To listen for a client, the program calls accept() method of ServerSocket as
in
Socket connection = server.accept();
 This statement returns a Socket object when a connection with a client is
established.
TCP Server Sockets…
 If you’re finished with a server socket, you should close it, especially if the
program is going to continue to run for some time.
 This frees up the port and other programs may use it if necessary.
 Closing a ServerSocket should not be confused with closing a Socket.
 Closing a ServerSocket frees a port on the local host and it also breaks all
currently open sockets that the ServerSocket has accepted.
 Server sockets are closed automatically when a program dies, so it’s not
absolutely necessary to close them.
 Nonetheless, it is a good practice to close the socket before the program
ends.
 Programmers often follow the approach “close if-not-null” in finally block.
TCP Server Sockets…
Example: closing ServerSocket
ServerSocket server = null;
try {
server = new ServerSocket(port);
//work with the server socket
} finally {
if (server != null) {
try {
server.close();
} catch (IOException ex) {
//ignore
}
}
Client Connection
 A socket is a connection between two hosts.
 The Socket class is Java’s fundamental class for performing client-side TCP
operations.
 Other client-oriented classes that make TCP network connections such as URL,
URLConnection, HttpURLConnection, Applet, and JEditorPane all ultimately end
up invoking the methods of this class.
 The Socket class itself uses native code to communicate with the local TCP stack of
the host operating system.
 Socket can perform four basic operations: connect to a remote machine, send data,
receive data, and close a connection.
 Java programs normally use client sockets in the following fashion:
 the program creates a new socket using a constructor

 the socket attempts to connect to the remote host

 Once connection established, the local and remote hosts get input and output

streams from the socket and use those streams to send data to each other.
 The connection established by Socket is full-duplex where both hosts can send and
receive data simultaneously.
Client Connection…
 The Socket class constructor specifies the host and the port to connect to.
 Hosts may be specified as an InetAddress or a String.
 Remote ports are specified as int values from 1 to 65535:
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress host, int port) throws IOException
 These constructors connect the server socket i.e. an active network connection is
established to the remote host.
 If the connection can’t be opened for some reason, the constructor throws an
IOException or an UnknownHostException.
 Example: client connection to a server
try {
Socket ss = new Socket("10.140.150.20", 80);
// send and receive data...
} catch (UnknownHostException ex) {
System.err.println(ex);
Client Connection…
 Once Socket is created, it is possible to start sending and receiving data
after that.
 If the socket cannot be opened for some reason, the constructor throws an
IOException.
 There are many reasons a connection attempt might fail: the host you’re
trying to reach may not accept connections on that port, or routing
problems may be preventing your packets from reaching their destination.
 Because this constructor doesn’t just create a Socket object but also tries to
connect the socket to the remote host, you can use the object to determine
whether connections to a particular port are allowed.
 Using this, you can write a port scanner that checks which ports are
occupied and which ports are available.
Method Description
It returns an input stream for reading bytes from this socket. IOException - if an I/O
InputStream getInputStream() error occurs when creating the input stream, the socket is closed, the socket is not
connected, or the socket input has been shutdown.
It returns an output stream for writing bytes to this socket. It throws IOException if
OutputStream getOutputStream() an I/O error occurs when creating the output stream or if the socket is not
connected.
Returns the connection state of the socket. Returns true if the socket was
boolean isConnected()
successfully connected to a server
Closes this socket. Any thread currently blocked in an I/O operation upon this socket
void close()
will throw a SocketException.
boolean isClosed() Returns the closed state of the socket. Returns true if the socket has been closed.
Returns whether the read-half of the socket connection is closed. Returns true if the
boolean isInputShutdown()
input of the socket has been shutdown.
Returns whether the write-half of the socket connection is closed. Returns true if the
boolean isOutputShutdown()
output of the socket has been shutdown.
int getPort() Returns the remote port number to which this socket is connected.
int getLocalPort() Returns the local port number to which this socket is bound.
It returns the remote IP address to which this socket is connected, or null if the
InetAddress getInetAddress()
socket is not connected.
InetAddress getLocalAddress() Gets the local address to which the socket is bound.
The method suggests a number of bytes to use for buffering output on this socket.
setSendBufferSize(int size)
The OS is free to ignore this suggestion.
int getSendBufferSize() Returns the value of the buffer size used by the platform for output on this Socket.
The method suggests a number of bytes to use for buffering input from this socket.
setReceiveBufferSize(int size)
However, the underlying implementation is free to ignore this suggestion.
int getreceiveBufferSize() It returns the actual size of the receive buffer.
private ServerSocket serverSocket;
Example: server side that waits for clients to
public ServerListening() {
connect to it
try {
serverSocket = new ServerSocket(110);
startServer();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public void startServer() {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
while (true) {
try {
Socket socket = serverSocket.accept();
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
DataInputStream in = new DataInputStream(socket.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("Thank you for connecting to " + socket.getLocalSocketAddress());
out.writeUTF("\nGoodbye!");
socket.close();
}catch (IOException e) {
e.printStackTrace(); break;
}
Example: a client program that connects to a server by using a socket and sends a
greeting, and then waits for a response.
public class ClientConnection {
public static void main(String[] args) {
String serverName = "10.120.130.140";
int port = 110;
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from client");

InputStream inFromServer = client.getInputStream();


DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Connection…
 When you create a server socket, you have to specify a port (e.g. 800) for
the socket.
 When a client connects to the server, a socket is created on the client.
 This socket has its own local port.
 This port number (e.g. 2047) is automatically chosen by the JVM.

 To see the local port on the client, you can write the following code on the
client side
System.out.println("local port: " + socket.getLocalPort());
Client Connection…
 The close() method shuts down both input and output from the socket by
closing the socket.
 On occasion, you may want to shut down only half of the connection,
either input or output.
 The shutdownInput() and shutdownOutput() methods close only half the
connection:
void shutdownInput()
void shutdownOutput()
 Neither actually closes the socket.
 Instead, they adjust the stream connected to the socket so that it thinks it’s
at the end of the stream.
 Further reads from the input stream after shutting down input return –1.
 Further writes to the socket after shutting down output throw an
IOException.
Client Connection…
Reading from and Writing to Sockets
 After the server accepts the connection and Socket is created, communication

between server and client is conducted using I/O streams.


 The InputStream and OutputStream streams are used to read or write bytes to

sockets.
 To get an input stream, use the getInputStream() method on a socket object.

 To get an output stream, use the getOutputStream() method on a socket

object.
 For example, the following statements create an InputStream stream and an

OutputStream stream from a socket:


InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
 The InputStream and OutputStream streams are used to read or write bytes.

 You can use DataInputStream, DataOutputStream, BufferedReader, and

PrintWriter to wrap on the InputStream and OutputStream to read or write


Client Connection…
 The following statements, for instance, create a DataInputStream
stream and a DataOutputStream stream to read and write primitive data
values:
DataInputStream input = new DataInputStream (socket.getInputStream());
DataOutputStream output = new DataOutputStream (socket.getOutputStream());
 The server can use input.readDouble() to receive a double value from
the client, and output.writeDouble(d) to send double value d to the
client.
public class CircleServer extends JFrame {
private JTextArea jta = new JTextArea();
public CircleServer() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
while (true) {
Socket socket = serverSocket.accept();
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
//receive radius from the client
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
//send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area computed: " + area + '\n');
}
} catch (IOException ex) { System.err.println(ex); }
}}
public class CircleClient extends JFrame { class TextFieldListener implements ActionListener {
private JTextField jtf = new JTextField(); public void actionPerformed(ActionEvent e) {
private JTextArea jta = new JTextArea(); try {
private DataOutputStream toServer; double radius = Double.parseDouble(jtf.getText());
private DataInputStream fromServer;
//send radius to server
public CircleClient() {
toServer.writeDouble(radius);
JPanel p = new JPanel();
toServer.flush();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
// Get area from the server
p.add(jtf, BorderLayout.CENTER);
double area = fromServer.readDouble();
jtf.setHorizontalAlignment(JTextField.RIGHT);
jta.append("Radius is " + radius + "\n");
setLayout(new BorderLayout());
jta.append("Area received : " + area + '\n');
add(p, BorderLayout.NORTH);
add(new JScrollPane(jta), BorderLayout.CENTER); } catch (IOException ex) {
jtf.addActionListener(new TextFieldListener()); System.err.println(ex);
setTitle("Client"); }
setSize(500, 300); }
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}
setVisible(true); // It is necessary to show the frame here!
try {
// Create a socket to connect to the server
Socket socket = new Socket("localhost", 8000);
fromServer = new DataInputStream(socket.getInputStream());
toServer = new DataOutputStream(socket.getOutputStream());
} catch (IOException ex) { jta.append(ex.toString() + '\n'); }
}
Client Connection…
Serving Multiple Clients
 Multiple clients are quite often connected to a single server at the same time.

 Typically, a server runs continuously on a server computer, and clients from all

over the Internet/LAN can connect to it.


 You can use threads to handle the server’s multiple clients simultaneously.

 Simply create a thread for each connection.

ServerSocket serverSocket = new ServerSocket(110);


while (true) {
Socket socket = serverSocket.accept(); //connect to a client
Thread thread = new ThreadClass(socket);
thread.start();
}
 This server socket can have many connections.

 Whenever a connection is established, a new thread is created to handle


communication between the server and the new client; and this allows
Client Connection…
 The CircleServer example given above can only serve a single
client at a time.
 It cannot accept multiple connections from different clients at
the same time.
 This is a big limitation for the server which is expected to
serve multiple clients.
 This problem can be solved by using thread.
 The following example shows how to do that.
public class ThreadedCircleServer extends JFrame {
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new ThreadedCircleServer();
}
public ThreadedCircleServer() {
setLayout(new BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
//loop and accept multiple connections
while (true) {
Socket socket = serverSocket.accept();
Communicate comm = new Communicate(socket);
comm.start();
}
} catch (IOException ex) { ex.printStackTrace(); }
}
class Communicate extends Thread {
Socket socket;
Communicate(Socket ss) {
socket = ss;
}
public void run() {
try {
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while (true) {
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;

outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area computed: " + area + '\n');
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
2.2 UDP Datagrams
 Some applications that you write to communicate over the network will not
require the reliable, point-to-point channel provided by TCP.
 Rather, your applications might benefit from a mode of communication that
delivers independent packages of information whose arrival and order of
arrival are not guaranteed.
 The UDP protocol provides a mode of network communication whereby
applications send packets of data, called datagrams, to one another.
 Datagrams are bundles of information passed between machines.
 A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
 Once the datagram has been released to its intended target, there is no
assurance that it will arrive at the destination.
 Likewise, when the datagram is received, there is no assurance that it
hasn’t been damaged in transit or that whoever sent it is still there to
receive a response.
UDP Datagrams…
 UDP is appropriate for data transfers where it doesn't matter if a packet is
lost in transition.
 For instance, imagine a transfer of a live TV-signal over the internet.
 You want the signal to arrive at the clients as close to live as possible.
 Therefore, if a frame or two are lost, you don't really care.
 You don't want the live broadcast to be delayed just to make sure all frames
are shown at the client.
 You'd rather skip the missed frames, and move directly to the newest
frames at all times.
 Java implements datagrams on top of the UDP protocol by using two
classes:
 the DatagramPacket which is the data container

 the DatagramSocket which is the mechanism used to send or receive the

DatagramPacket.
UDP Datagrams…
A. DatagramSocket
 A DatagramSocket sends as well as receives UDP datagrams.
 To send data, you put the data in a DatagramPacket and send the packet
using a DatagramSocket.
 To receive data, you take a DatagramPacket object from a DatagramSocket
and then inspect the contents of the packet.
 The DatagramSocket themselves are very simple creatures.
 In UDP, everything about a datagram, including the address to which it is
directed, is included in the packet itself.
 The socket only needs to know the local port on which to listen or send.
 DatagramSocket defines four public constructors.
 DatagramSocket() – this creates a DatagramSocket bound to

any unused port on the local computer.


 DatagramSocket(int port) – creates a DatagramSocket bound

to the port specified by port.


 DatagramSocket(int port, InetAddress ip) – constructs a

DatagramSocket bound to the specified port and InetAddress.


 DatagramSocket(SocketAddress address) – this creates a

DatagramSocket bound to the specified SocketAddress.


InetSocketAddress encapsulates an IP address with a port
number.
 All can throw a SocketException if an error occurs while
creating the socket.
 DatagramSocket defines many methods.
 Two of the most important are send() and receive():
 send(DatagramPacket packet) – this method sends a packet to
the address specified by packet.
 The DatagramPacket includes information indicating the data to be
sent, its length, the IP address of the remote host, and the port
number on the remote host. It throws IOException if there is an
input-output error.
 receive(DatagramPacket packet) – this method waits for a
packet to be received and returns the result. When this method
returns, the DatagramPacket's buffer is filled with the data
received. This method blocks until a datagram is received. It
throws IOException if there is an input output error.
UDP Datagrams…
 Other methods of DatagramSocket:
Method Description
If a DatagramSocket is connected, the getInetAddress() method
InetAddress getInetAddress() returns the address of the remote host to which it is connected.
Otherwise, it returns null.
int getLocalPort() Returns the number of the local port.
If a DatagramSocket is connected, the getPort() method returns the
int getPort()
remote port to which it is connected. Otherwise, it returns –1.
Returns true if the socket is bound to an address. Returns false
boolean isBound()
otherwise.
Returns true if the socket is connected to a server. Returns false
boolean isConnected()
otherwise.

Sets the time-out period to the number of milliseconds passed


waiting for data. With this option set to a non-zero timeout, a call to
void setSoTimeout(int millis)
receive() for this DatagramSocket will block for only this amount of
time. If the timeout expires, a SocketTimeoutException is raised.
UDP Client
 Both UDP server and UDP client are created using DatagramSocket.

 The only difference is the port they bind to: the server socket should bind

to fixed port whereas the client should not.


 Let us retrieve some data programmatically using UDP client.

 First, open a socket on port 0:

DatagramSocket socket = new DatagramSocket(0);


 You only specify a local port to connect to.

 The socket does not know the remote host or address.

 By specifying port 0 you ask Java to pick a random available port for you,

much as with server sockets.


 Next step is to set a timeout on the connection using the setSoTimeout()

method.
 This tells the socket to time out after 10 seconds of non-responsiveness:

socket.setSoTimeout(10000);
 Timeouts are even more important for UDP than TCP because many

problems that would cause an IOException in TCP silently fail in UDP.


 For example, if the remote host is not listening on the targeted port, you’ll

never hear about it.


UDP Server
 A UDP server follows almost the same pattern as a UDP client, except that
you usually receive data before sending & also use a fixed port to bind to.
 Unlike TCP, there’s no separate DatagramServerSocket class.
 To create UDP server, begin by opening a datagram socket on a well-
known port.
DatagramSocket socket = new DatagramSocket(13);
 Next, create a packet into which to receive a request.
 You need to supply both a byte array in which to store incoming data, the
offset into the array, and the number of bytes to store.
 Here you set up a packet with space for 1,024 bytes starting at 0:
DatagramPacket request = new DatagramPacket(new byte[1024], 0, 1024);
socket.receive(request);
 This call blocks indefinitely until a UDP packet arrives on port 13.
 When it does, Java fills the byte array with data and the receive() method
returns.
2.2 UDP Datagrams…
B. DatagramPacket
 To send data via Java's DatagramSocket you must first create a
DatagramPacket.
 DatagramPacket objects store packets of data for sending or store packets of
data received by an application.
 DatagramSockets send and receive DatagramPackets.
 DatagramPacket defines several constructors.
 Some of these constructors are for creating a DatagramPacket for receiving
data while others are for sending data.
 For receiving data with DatagramPacket, you can use the following
constructors:
 DatagramPacket(byte data [], int size) – this specifies a buffer that will

receive data and the size of a packet. It is used for receiving data over a
DatagramSocket.
 DatagramPacket(byte data [], int offset, int size) - the second form allows
2.2 UDP Datagrams…
 For sending packets, you can create DatagramPacket using the following
constructors:
 DatagramPacket(byte data [], int length, InetAddress ip, int port) - this
specifies a target address and port, which are used by a DatagramSocket
to determine where the data in the packet will be sent.
 DatagramPacket(byte data [], int offset, int length, InetAddress ip, int
port) – same as the above method except this transmits packets beginning
at the specified offset into the data.
 DatagramPacket(byte[] data, int length, SocketAddress destination) –
creates a datagram packet for sending packets of the given length to the
computer specified by SocketAddress.
 DatagramPacket(byte[] data, int offset, int length, SocketAddress
destination) – creates a datagram packet for sending packets of the given
length starting from the given offset. The data is sent to the specified port
number and the machine specified with the given SocketAddress.
 DatagramPacket Methods
Method Description
Returns the address of the source (for datagrams being received) or
InetAddress getAddress( )
destination (for datagrams being sent).
Returns the byte array of data contained in the datagram. Mostly used
byte[] getData( )
to retrieve data from the datagram after it has been received.
Returns the length of the valid data contained in the byte array that
int getLength( ) would be returned from the getData() method. This may not equal the
length of the whole byte array.
int getOffset( ) Returns the starting index of the data.
The method returns an integer specifying the remote port. If this
datagram was received from the Internet, this is the port on the host
int getPort( ) that sent the packet. If the datagram was created locally to be sent to a
remote host, this is the port to which the packet is addressed on the
remote machine.
void setPort(int port) This method sets the port a datagram is addressed to.
Sets the address to which a packet will be sent. The address is specified
setAddress(InetAddress ip)
by InetAddress.
Sets the data to data, the offset to zero, and the length to number of
void setData(byte[ ] data)
bytes in data.
setData(byte[ ] data, int idx,
Sets the data to data, the offset to idx, and the length to size.
int size)
void setLength(int size) Sets the length of the packet to size.
 Example: UDP server that sends hello message to all clients
DatagramSocket sock = null;
Scanner sc = new Scanner(System.in);
try {
sock = new DatagramSocket(7777);
//buffer to receive incoming data
byte[] buffer = new byte[8192];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
System.out.println("Server socket created. Waiting for incoming data...");
//communication loop
while (true) {
sock.receive(incoming);
byte[] data = incoming.getData();
String str = new String(data, 0, incoming.length, “”);
System.out.println("Client: " + str);
System.out.print("Server: ");
String msg = sc.nextLine();
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.getBytes().length,
incoming.getAddress(), incoming.getPort());
sock.send(dp);
}
} catch (IOException e) {
System.err.println("IOException " + e);
}
Example: UDP client that can connect to the above UDP server
DatagramSocket sock = null;
String str;
Scanner sc = new Scanner(System.in);
try {
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
int port = 7777;
while (true) {
System.out.print("Client: ");
str = sc.nextLine();
byte[] b = str.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, host, port);
sock.send(dp);
//now receive reply
byte[] buffer = new byte[8192];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
String msg = new String(data, 0, reply.length);
System.out.println("Server: " + msg);
}
} catch (IOException e) { System.err.println("IOException " + e); }
REMOTE METHOD
INVOCATION
What is RMI?
 The Remote Method Invocation (RMI) system allows an object running in one
machine to invoke methods on an object running in another machine.
 RMI provides remote communication between programs written in the Java
programming language.
 RMI applications often comprise two separate programs: a server and a client.
 A server program creates remote objects, makes references to these objects
accessible, and 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.
 RMI provides the mechanism by which the server and the client communicate
and pass information back and forth.
 Such an application is sometimes referred to as a distributed object application.
 A remote object is an object whose methods can be invoked from another JVM
that may be running on a different host.
 The object is described by remote interfaces that declare available methods.
What is RMI...
 RMI is designed in order to support the distributed object model.
 The system architecture consists of three basic layers: the stub/skeleton
layer, remote reference layer, and transport.
 A specific interface and protocol defines the boundary at each layer.
 Thus, each layer is independent of the next and can be replaced by an
alternate implementation without affecting the other layers in the system.
 For example, the current transport implementation is TCP based (using
Java sockets), but a transport based on UDP could be used
interchangeably.

Fig RMI system architecture


What is RMI...
 The stub/skeleton layer is the interface between the application layer and
the rest of the RMI system.
 This layer does not deal with specifics of any transport, but transmits data
to the remote reference layer.
 A client invoking a method on a remote server object actually makes use
of a stub or proxy for the remote object as a conduit to the remote object.
 A client-held reference to a remote object is a reference to a local stub.
 This stub is an implementation of the remote interfaces of the remote
object and forwards invocation requests to that server object via the
remote reference layer.
 A stub for a remote object is the client-side proxy for the remote object.
 Such a stub implements all the interfaces that are supported by the remote
object implementation.
What is RMI...
 A skeleton for a remote object is a server-side entity that contains a method
which dispatches calls to the actual remote object implementation.
 The skeleton is responsible for:
 unmarshaling arguments from the marshal stream

 making the up-call to the actual remote object implementation

 marshaling the return value of the call onto the marshal stream

 In general, RPC systems apply a double transformation to input and output


parameters to solve problems related to heterogeneous representations:
 marshalling: action that codes arguments and results to be transmitted

 unmarshalling: reverse action that decodes arguments and results

 The objects are simply serialized/deserialized using mechanisms provided by


the language.
 serialization: transformation of complex objects into simple byte

sequences
 deserialization: decoding of a byte sequence and building of a copy of the
 RRL manages remote references, parameters and stream-oriented
connection abstraction.
 The remote reference layer is responsible for carrying out the semantics of
the type of invocation.
 For example this layer is responsible for handling unicast or multicast
invocation to a server.
 Each remote object implementation chooses its own invocation semantics —
whether communication to the server is unicast, or the server is part of a
multicast group.
 The transport is responsible for connection set-up with remote locations
and connection management, and also keeping track of and dispatching to
remote objects residing in the transport’s local address space.
 The transport layer sets up the connections to remote address spaces,
manages them, monitors the connection liveliness, and listens the incoming
calls.
 In order to dispatch to a remote object, the server’s transport forwards the
remote call up to the remote reference layer (specific to the server).
 The remote reference layer handles any server-side behavior that needs to be
done before handing off the request to the server-side skeleton.
 The skeleton for a remote object makes an up-call to the remote object
What is RMI...
 RMI communicates as follows:
1. The client obtains a stub instance
2. The client calls the desired methods on the stub and waits for result
3. The stub:
 Serializes the information needed for the method invocation (method id

and arguments)
 Sends information to the skeleton exploiting the RRL abstractions

4. The skeleton:
 Deserializes the received data

 Calls the method on the object that implements the server (dispatching)

 Serializes the return value and sends it to the stub

5. The stub:
 Deserializes the return value

 Returns the result to the client


What is RMI...
 Distributed object applications need to do the following:
 Locate remote objects: applications can use various mechanisms to obtain
references to remote objects.
 For example, an application can register its remote objects with RMI's
simple naming facility, the RMI registry.
 Alternatively, an application can pass and return remote object references
as part of other remote invocations.
 Communicate with remote objects: details of communication between
remote objects are handled by RMI.
 To the programmer, remote communication looks similar to regular Java
method invocations.
 Load class definitions for objects that are passed around: because RMI
enables objects to be passed back and forth, it provides mechanisms for
loading an object's class definitions as well as for transmitting an object's
data.
What is RMI...
 The following illustration depicts an RMI distributed application that uses
the RMI registry to obtain a reference to a remote object.
 The server calls the registry to associate (or bind) a name with a remote
object…to obtain reference to an object
 The client looks up the remote object by its name in the server's registry
and then invokes a method on it.
 The RMI registry is used to obtain references to a remote object.
 First the server associates a name with a remote object in the RMI registry.
 When a client wants access to a remote object it looks up the object, by its
name, in the registry.
 Then the client can invoke methods on the remote object at the server.
What is RMI...

Fig RMI components

 RMI is the Java Distributed Object Model for facilitating communications


among distributed objects.
 RMI is a higher-level API built on top of sockets.
 Socket-level programming allows you to pass data through sockets among
computers.
 RMI enables you not only to pass data among objects on different systems,
but also to invoke methods in a remote object.
Remote Interfaces, Objects, and Methods

 A distributed application built by using Java RMI is made up of


interfaces and classes.
 The interfaces declare methods to be called by clients.
 The classes implement the methods declared in the interfaces and,
perhaps, declare additional methods as well.
 In a distributed application, some implementations might reside in some
Java virtual machines but not others.
 Objects with methods that can be invoked across JVMs are
called remote objects.
 An object becomes remote by implementing a remote interface, which
has the following characteristics:
 A remote interface extends the interface java.rmi.Remote

 Each method of the interface throws java.rmi.RemoteException using

throws clause, in addition to any application-specific exceptions


Remote Interfaces, Objects, and...

 RMI treats a remote object differently from a non-remote object when the
object is passed from one JVM to another JVM.
 Rather than making a copy of the implementation object in the receiving JVM,
RMI passes a remote stub for a remote object.
 The stub acts as the local representative, or proxy, for the remote object and
basically is, to the client, the remote reference.
 The client invokes a method on the local stub, which is responsible for
carrying out the method invocation on the remote object.
 A stub for a remote object implements the same set of remote interfaces that
the remote object implements.
 This property enables a stub to be cast to any of the interfaces that the remote
object implements.
 However, only those methods defined in a remote interface are available to be
Designing and Implementing the Application Components
 First, determine your application architecture, including which components
are local objects and which components are remotely accessible. This step
includes:
 Defining the remote interfaces:
 A remote interface specifies the methods that can be invoked remotely by a client.
 Clients program to remote interfaces, not to the implementation classes of those
interfaces.
 The design of such interfaces includes the determination of the types of objects that
will be used as the parameters and return values for these methods.
 If any of these interfaces or classes do not yet exist, you need to define them as well.
 Implementing the remote objects:
 Remote objects must implement one or more remote interfaces.
 The remote object class may include implementations of other interfaces and
methods that are available only locally.
 If any local classes are to be used for parameters or return values of any of these
methods, they must be implemented as well.
 Implementing the clients:
 Clients that use remote objects can be implemented at any time after the remote
interfaces are defined, including after the remote objects have been deployed.
Remote Server
 The server code consists of a remote interface and a class that
implements the remote interface.
 The interface defines the methods that can be invoked from the
client.
 Essentially, the interface defines the client's view of the remote
object.
 The class provides the implementation by implementing the
interface.
Remote Server…
A. Remote Interface
 A remote interface extends the interface java.rmi.Remote

 It declares a set of remote methods.

 By extending the java.rmi.Remote interface, any interface identifies itself as an

interface whose methods can be invoked from another machine.


 Any object that implements this interface can be a remote object.

 A method of the remote interface is a remote method.

 All such methods must be defined as being capable of throwing a

java.rmi.RemoteException.
 This exception is thrown by the RMI system from a remote method invocation

to indicate that either a communication failure or a protocol error has occurred.


 Example: a remote interface definition

public interface AddInterface extends Remote{


double add(double d1, double d2) throws RemoteException;
}
Remote Server…
B. Remote Object
 An RMI server program needs to create remote objects and export them to
the RMI runtime, which makes them available to receive incoming remote
invocations.
 The server contains a class that extends UnicastRemoteObject and
implements the remote interface.
 UnicastRemoteObject is used for exporting a remote object with Java
Remote Method Protocol (JRMP) and obtaining a stub that communicates
to the remote object.
 The server class can also have additional methods, but only the methods in
the remote interface will be available to the client.
 This is the case because the client will get only a handle to the interface,
not the class that implements it.
 UnicastRemoteObject supplies implementations for a number of
java.lang.Object methods so that they are defined appropriately for remote
objects.
Remote Server…
 UnicastRemoteObject also includes constructors and static methods used to
export a remote object, that is, make the remote object available to receive
incoming calls from clients.
 When the remote object extends the UnicastRemoteObject, the default
constructor of the UnicastRemoteObject class automatically exports the
subclass to RMI runtime.
 Hence, no exporting code should be written in the program.
 Example: remote class that implements remote interface
import java.rmi.*;
import java.rmi.server.*;
public class AddServer extends UnicastRemoteObject implements AddInterface {
public AddServer() throws RemoteException { }
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
}
Remote Server…
 A remote object implementation does not have to extend
UnicastRemoteObject.
 But any implementation that does not extend must supply appropriate
implementations of the java.lang.Object methods.
 Furthermore, a remote object implementation must make an explicit call to
one of UnicastRemoteObject's exportObject methods to make the RMI
runtime aware of the remote object so that the object can accept incoming
calls.
 By extending UnicastRemoteObject, any class can be used to create a
simple remote object that supports unicast (point-to-point) remote
communication and that uses RMI's default sockets-based transport for
communication.
 You must explicitly define the constructor for the remote object even if
you’re only defining a default constructor that calls the base-class
constructor.
Remote Server…
Skeletons and Stubs
 Before you can use the client and server, you must first generate the

necessary stub and may also need to generate a skeleton.


 A stub is a Java object that resides on the client machine.

 Its function is to present the same interfaces as the remote server.

 Remote method calls initiated by the client are actually directed to the stub.

 A skeleton is a Java object that resides on the server machine.

 It works with the other parts of the RMI system to receive requests,

perform deserialization, and invoke the appropriate code on the server.


 But, the skeleton mechanism is not required for Java 2 code.

 To generate stubs and skeletons, you use a tool called the RMI compiler,

which is invoked from the command line, as shown here:


rmic classname
where classname is the server class that implements the remote interface.
RMI Registry
 Before a client can invoke a method on a remote object, it must first
obtain a reference to the remote object.
 The system provides the RMI registry for finding references to
remote objects.
 The RMI registry is a simple remote object naming service that
enables clients to obtain a reference to a remote object by name.
 The registry is typically only used to locate the first remote object
that an RMI client needs to use.
 That first remote object might then provide support for finding other
objects.
RMI Registry
 The java.rmi.registry.Registry remote interface is the API for
binding/registering and looking up remote objects in the registry.
 The java.rmi.registry.LocateRegistry is used to obtain a reference to a
registry on a particular host (including the local host), or to create a registry
that accepts calls on a specific port.
 The java.rmi.registry.LocateRegistry class provides static methods for
synthesizing a remote reference to a registry at a particular network address
(host and port).
 LocateRegistry also provides static methods for creating a new registry in
the current Java virtual machine.
 Once a remote object is registered with an RMI registry on the local host,
clients on any host can look up the remote object by name, obtain its
reference, and then invoke remote methods on the object.
 The registry can be shared by all servers running on a host, or an individual
server process can create and use its own registry.
RMI Registry
 The getRegistry() method of LocateRegistry:
 static Registry getRegistry(String host) - it returns a reference to
Registry on the specified host on the default registry port of 1099.
 If host is null, the local host is used.
 It throws RemoteException.
 Example: registering an instance of remote object onto registry
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, object);
 This rebind invocation makes a remote call to the RMI registry on
the localhost.
 Like any remote call, this call can result in a RemoteException
being thrown, which is handled by the catch block at the end of
the main method.
RMI Registry
 Methods of Registry
Method Description

void bind(String name, Binds a remote reference to the specified name in this registry. It
Remote obj) throws RemoteException, AlreadyBoundException, AccessException.

Replaces the binding for the specified name in this registry with the
void rebind(String name, supplied remote reference. If there is an existing binding for the
Remote obj) specified name, it is discarded. It throws RemoteException,
AccessException.

void unbind(String name) Removes the binding for the specified name in this registry. It
throws RemoteException, NotBoundException, AccessException

Remote lookup(String It returns the remote reference bound to the specified name in this
name) registry. It throws RemoteException, NotBoundException,
AccessException.

Returns an array of the names bound in this registry. The array will
String[] list() contain a snapshot of the names bound in this registry. It throws
RemoteException, AccessException.
RMI Registry
 Note the following about the Registry.rebind invocation:
 The no-argument version of LocateRegistry.getRegistry synthesizes a
reference to a registry on the localhost & on the default registry port, 1099.
You must use an overload that has an int parameter if the registry is
created on a port other than 1099.
 When a remote invocation on the registry is made, a stub for the remote
object is passed instead of a copy of the remote object itself. Remote
implementation objects, such as instances of AddServer, never leave the
JVM in which they were created. Thus, when a client performs a lookup in
a server's remote object registry, a copy of the stub is returned. Remote
objects in such cases are thus effectively passed by reference rather than
by value.
 For security reasons, an application can only bind, unbind, or rebind
remote object references with a registry running on the same host. This
restriction prevents a remote client from removing or overwriting any of
the entries in a server's registry. A lookup, however, can be requested from
any host, local or remote.
RMI Registry
 The Naming class provides methods for storing and obtaining
references to remote objects in a remote object registry.
 Each method of the Naming class takes as one of its arguments a
name that is a String in URL format of the form:
rmi://host:port/name
 Before clients can lookup remote objects on RMI registry, the
registry first should be started.
 To start the RMI Registry from the command line, use the following
command:
start rmiregistry
RMI Registry…
 Methods of Naming class
Method description
It returns a reference, a stub, for the remote object
associated with the specified name. The method throws
static Remote lookup(String name) NotBoundException, MalformedURLException, and
RemoteException.
It binds the remote object with the given name. It throws
static void bind(String name, Remote r) AlreadyBoundException, MalformedURLException, and
RemoteException.
It destroys the remote object which is bound with the given
static void unbind(String name) name. It throws RemoteException, NotBoundException, and
MalformedURLException.
It rebinds the specified name to a new remote object. Any
static void rebind(String name, Remote r) existing binding for the name is replaced. It throws
RemoteException, and MalformedURLException.
It returns an array of the names of the remote objects bound
static String[] list(String name) to the registry. The name parameter is a registry name in URL
format. It throws RemoteException, and
MalformedURLException.
RMI Registry…
 What is the difference between Naming and registry?
 The difference is that the name arguments you pass to java.rmi.Naming are
in URL format, and include the location of the registry, whereas with
java.rmi.registry.Registry, the name is just the name.
 Also, the methods on Naming are static.
 For example, you would call something like this:
Naming.rebind("//host/objName", myObj);
 Whereas with Registry, you need an existing handle on the registry object,
and you'd call:
Registry registry =LocateRegistry.getRegistry();
registry.rebind("objName", myObj);
 Generally, Naming is really just a convenience class that saves you having
to look up the Registry manually because it performs the registry lookup
and rebind in one step.
RMI Client
 The client class does not have to do much to access the RMI
server.
 The only thing the client should do is get reference of remote
object in order to call its methods.
 This is done using the Naming class.
 Once the client gets reference of remote object, it can call the
remote methods.
 Example: RMI that accepts two numbers, add them and display the result on client
//remote interface
public interface AddInterface extends Remote{
Server side
double add(double d1, double d2) throws RemoteException;
}
//remote object
public class AddServer extends UnicastRemoteObject implements AddInterface {
public AddServer() throws RemoteException { }
public double add(double d1, double d2) throws RemoteException {
return d1 + d2;
}
public static void main(String args[]) {
try {
AddServer addServer = new AddServer ();
Naming.bind("AddServerObject", addServer);
System.out.println("Server started...");
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}}
//remote interface
public interface AddInterface extends Remote{
double add(double d1, double d2) throws RemoteException;
} Client side
//client
public class AddClient {
public static void main(String args[]) {
try {
String addServerURL = "rmi://localhost/AddServerObject";
AddInterface addServerIntf = (AddInterface) Naming.lookup(addServerURL);

Scanner sc = new Scanner(System.in);


System.out.println("Enter two numbers: ");
double d1 = sc.nextDouble();
double d2 = sc.nextDouble();
System.out.println("Numbers: " + d1 + " " + d2);
System.out.println("The sum is: " + addServerIntf.add(d1, d2));
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
RMI Client…
 If your remote server is not extending UnicastRemoteObject, then you
have to export the remote object.
 The remote object must be exported to the Java RMI runtime so that it
may receive incoming remote calls.
 This can be done using exportObject() method of
UnicastRemoteObject.
 The general syntax is:
static Remote exportObject(Remote obj, int port)
 The method exports the remote object to make it available to receive
incoming calls, using the particular supplied port.
//remote interface
public interface Hello extends Remote {
String sayHello() throws RemoteException;
} Server side
//remote server
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.out.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
}
}
}
//client
public class Client {
private Client() {} Client side
public static void main(String[] args) {
String host = "localhost";
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

You might also like