Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
Client-Server Communication
• Sockets
• Remote Procedure Calls
• Remote Method Invocation (Java)
Sockets
• RMI
– Register method as remotely accessible
• Client can look up method and receive a reference
• Use reference to call method
• Syntax same as a normal method call
– Marshalling of data
• Can transfer objects as well
• Class ObjectOutputStream converts Serializable
object into stream of bytes
– Transmit across network
• Class ObjectInputStream reconstructs object
– No Interface Definition Language needed
• Use Java's own interface
Case Study: Creating a Distributed System with
RMI
• RMI example
– Downloads weather information from National Weather
Service website
http://iwin.nws.noaa.gov/iwin/us/traveler.html
• Note: Format of website changed several times, if example does
not work do the appropriate modifications.
– Store information on a server
• Request information through remote method calls
Case Study: Creating a Distributed System
with RMI
Case Study: Creating a Distributed System with
RMI
• Four major steps
– Define remote interface
• Describes client/server communication
– Define server application to implement remote interface
• Same name as remote interface, ends with Impl
– Define client application that uses remote interface reference
• Interacts with server implementation
– Compile and execute server and client
Defining the Remote Interface
• First step
– Define remote interface that describes remote methods
• Client calls remote methods, server implements them
• To create a remote interface
– Define interface that extends interface Remote
(java.rmi)
• Tagging interface - no methods to define
• An object of a class that implements interface Remote directly
or indirectly is a remote object and can be accesses from any
JVM.
– Each method in Remote interface must throw
RemoteException
• Potential network errors
Defining the Remote Interface
• Interface TemperatureServer
– Extends Remote
– Describes method getWeatherInfo
1// Fig. 20.1: TemperatureServer.java
2// TemperatureServer interface definition
2. getWeatherInfo
Methods in Remote interface (is a relationship)
must be able to throw a RemoteException. 2.1 throws
RemoteException
Implementing the Remote Interface
• Define TemperatureServerImpl
– Implements Remote interface TemperatureServer
– Client interacts with TemperatureServerImpl object
– Uses array of WeatherInfo objects to store data
• Copy sent to client when calls getWeatherInfo
Implementing the Remote Interface
18 public class TemperatureServerImpl extends UnicastRemoteObject
19 implements TemperatureServer {
– UnicastRemoteObject
• Provides functionality for remote objects
• Constructor exports object so it can receive remote calls
– Wait for client on anonymous port number
22 public TemperatureServerImpl() throws RemoteException
– URL object
• Contains URL for Traveler's Forecast web page
• Throws MalformedURLException
Implementing the Remote Interface
40 BufferedReader in =
41 new BufferedReader(
42 new InputStreamReader( url.openStream() ) );
51 String s1 =
52 "CITY WEA HI/LO WEA HI/LO";
– WeatherInfo objects
• City name, temperature, description of weather
– Method substring to extract data from line
• Store all WeatherInfo objects in a Vector
84 weatherInformation[ i ] =
85 ( WeatherInfo ) cityVector.elementAt( i );
– Close connection
Implementing the Remote Interface
116 String serverObjectName = "//localhost/TempServer";
3import java.rmi.*;
4
1. Interface
5public interface TemperatureServer extends Remote { ------------------
6 public WeatherInfo[] getWeatherInfo()
7 throws RemoteException;
1. extends
8}
UnicastRemote
9TemperatureServer interface.
Object, implements
10 // Fig. 20.2: TemperatureServerImpl.java
TemperatureServer
11 // TemperatureServerImpl definition
12 import java.rmi.*;
13 import java.rmi.server.*; 1.1 Constructor
14 import java.util.*;
Allows objects to be exported.
15 import java.io.*;
16 import java.net.*;
17
35
40 BufferedReader in =
41 new BufferedReader( 2.3 readLine
42 new InputStreamReader( url.openStream() ) );
43
45
56
57 // locate header that begins weather information
58 do {
59 inputLine = in.readLine();
67 2.5.1 WeatherInfo
68 while ( !inputLine.equals( "" ) ) {
69 // create WeatherInfo object for city
72 inputLine.substring( 16, 22 ),
2.6 WeatherInfo array
73 inputLine.substring( 23, 29 ) );
74
77 }
78
Create WeatherInfo array, cast
79 // create array to return to client
Vector elements.
80 weatherInformation =
81 new WeatherInfo[ cityVector.size() ];
82
84 weatherInformation[ i ] =
85 ( WeatherInfo ) cityVector.elementAt( i );
86
87 System.err.println( "Finished Processing Data." );
89 }
90 catch( java.net.ConnectException ce ) {
93 }
94 catch( Exception e ) {
3. getWeatherInfo
95 e.printStackTrace();
96 System.exit( 1 ); 4. main
97 }
107 {
108 System.err.println(
114
115 // bind TemperatureServerImpl object to the rmiregistry
116 String serverObjectName = "//localhost/TempServer";
117 Naming.rebind( serverObjectName, temp );
118 System.err.println( 4.2
119 "The Temperature Server is up and running." ); server object. serverObjectName
Name of
120 }
121 } 4.3 rebind
rebind binds object to
rmiregistry.
1/ Fig. 20.3: WeatherInfo.java
5 1. Class WeatherInfo
6 public class WeatherInfo implements Serializable { implements
7 private String cityName;
Serializable
8 private String temperature;
10 1. Instance variables
11 public WeatherInfo( String city, String desc, String temp )
12 {
1.1 Constructor
13 cityName = city;
14 temperature = temp;
17
19
21
23 }
Define the client
• Next step
– Client code to get weather info from
TemperatureServerImpl
– Calls getWeatherInfo through RMI
– Graphically display weather info
• Class WeatherItem (extends JLabel) stores info about
each city
• Display name, High/low, and image (depending on conditions)
Define the client
22 private void getRemoteTemp( String ip )
26 String serverObjectName = "//" + ip + "/TempServer";
52 p.add( w[ i ] );
53 }
– Add WeatherItems
• Initialize with WeatherInfo
68 public static void main( String args[] )
69 {
70 TemperatureClient gt = null;
74 if ( args.length == 0 )
75 gt = new TemperatureClient( "localhost" );
76 else
77 gt = new TemperatureClient( args[ 0 ] );
– main
• Passes command line argument (ip) to constructor
• localhost default
Define the client
• Class WeatherItem
– extends JLabel
– static initializer block
• For complex initialization of static variables
• backgroundImage - ImageIcon, has background
• weatherImages - ImageIcon array, holds weather
images
18 static {
19 backgroundImage = new ImageIcon( "images/back.jpg" );
20 weatherImages =
21 new ImageIcon[ weatherImageNames.length ];
22
23 for ( int i = 0; i < weatherImageNames.length; ++i )
24 weatherImages[ i ] = new ImageIcon(
25 "images/" + weatherImageNames[ i ] + ".jpg" );
26 }
Define the client
39 if ( weatherConditions[ i ].equals(
40 weatherInfo.getDescription().trim() ) ) {
41 weather = weatherImages[ i ];
3import java.awt.*;
4import java.awt.event.*;
5import javax.swing.*;
6import java.rmi.*;
1. import
7
11 { 2. getRemoteTemp
12 super( "RMI TemperatureClient..." );
13 getRemoteTemp( ip );
14 2.1
15 setSize( 625, 567 );
serverObjectName
16 setResizable( false );
24 try {
29 // in rmiregistry
35 WeatherItem w[] =
Call2.3
likegetWeatherInfo
36 new WeatherItem[ weatherInfo.length ];
regular method.
37 ImageIcon headerImage =
39 2.4 GUI
40 JPanel p = new JPanel();
41
45 p.setLayout(
49
52 p.add( w[ i ] );
53 }
54
56 BorderLayout.CENTER );
57 }
58 catch ( java.rmi.ConnectException ce ) {
61 }
62 catch ( Exception e ) {
63 e.printStackTrace();
64 System.exit( 1 );
65 }
66 } 3. main
67
68 public static void main( String args[] )
3.1 args[ 0 ]
69 {
70 TemperatureClient gt = null;
71
72 // if no sever IP address or host name specified,
73 // use "localhost"; otherwise use specified host
74 if ( args.length == 0 )
75 gt = new TemperatureClient( "localhost" );
76 else args[ 0 ] is the first
77 gt = new TemperatureClient( args[ 0 ] ); argument, which should be
78 the IP address.
79 gt.addWindowListener(
80 new WindowAdapter() {
81 public void windowClosing( WindowEvent e )
82 {
83 System.exit( 0 );
84 }
85 }
86 );
87 }
88 }
1// Fig. 20.5: WeatherItem.java
3import java.awt.*;
4import javax.swing.*;
5
1. Class WeatherItem
6public class WeatherItem extends JLabel {
16
18 static {
20 weatherImages =
22
27
28 // instance variables
Use names in weatherImageNames
29 private ImageIcon weather;
array to load ImageIcons.
30 private WeatherInfo weatherInfo;
31
33 {
34 weather = null;
35 weatherInfo = w; 2. Constructor
36
40 weatherInfo.getDescription().trim() ) ) { 3. paintComponent
41 weather = weatherImages[ i ];
42 break;
47 // weather condition
48 if ( weather == null ) {
51 weatherInfo.getDescription() );
52 }
53 }
54
57 super.paintComponent( g );
58 backgroundImage.paintIcon( this, g, 0, 0 );
59
60 Font f = new Font( "SansSerif", Font.BOLD, 12 );
61 g.setFont( f );
62 g.setColor( Color.white );
63 g.drawString( weatherInfo.getCityName(), 10, 19 );
3.2 drawString
64 g.drawString( weatherInfo.getTemperature(), 130, 19 );
65
3.3 paintIcon
66 weather.paintIcon( this, g, 253, 1 );
67 }
68 Draw city name, high/low, and attach
69 // make WeatherItem's preferred size the width weather
and heightimage
of to WeatherItem.
70 // the background image
71 public Dimension getPreferredSize()
72 {
73 return new Dimension( backgroundImage.getIconWidth(),
74 backgroundImage.getIconHeight() );
75 }
76 }
Compile and Execute the Server and the Client
• Start rmiregistry
– Type rmiregistry at command window
• No text in response
Compile and Execute the Server and the Client
• Execute TemperatureClient
– java TemperatureClient
– If server on different machine, specify IP on command line
java TemperatureClient 192.168.150.4
– Result on next slide
Program Output