Chapter 20 - Remote Method Invocation (RMI)

Download Report

Transcript Chapter 20 - Remote Method Invocation (RMI)

Remote Method Invocation (RMI)
Client-Server Communication
• Sockets
• Remote Procedure Calls
• Remote Method Invocation (Java)
Sockets
• A socket is defined as an endpoint for communication.
• Concatenation of IP address and port
• The socket 161.25.19.8:1625 refers to port 1625 on host
161.25.19.8
• Communication consists between a pair of sockets.
• Considered a low-level form of communication between
distributed processes.
– Sockets allow only an unstructured stream of bytes to be
exchanged. It is the responsibility of the client or server application
to impose a structure on the data.
Socket Communication
Remote Procedure Calls
• Remote procedure call (RPC) abstracts procedure
calls between processes on networked systems.
• Stub – client-side proxy for the actual procedure
on the server. Server has a similar stub as well.
• The client-side stub locates the server and
marshals the parameters.
• The server-side stub receives this message,
unpacks the marshaled parameters, and performs
the procedure on the server.
• External data representation (XDR) I.e mostsignificant (big-endian), least-significant(littleendian)
Execution of RPC
Remote Method Invocation
• Remote Method Invocation (RMI) is a Java mechanism
similar to RPCs.
• RMI allows a Java program on one machine to invoke a
method on a remote object.
Marshalling Parameters
Remote Method Invocation
• RMI and RPC differs in two ways:
1. RPCs support procedural programming whereby only
remote procedures or functions may be called. RMI is
object based: It supports invocation of methods on remote
objects.
2. The parameters to remote procedures are ordinary data
structures in RPC; with RMI it is possible to pass objects
as parameters to remote methods.
• If the marshaled parameters are local (non remote) objects,
they are passed by copy using a technique known as object
serialization.
– Object serialization allowed the state of an object to be
written toa byte stream.
Introduction to RMI
• Remote Method Invocation (RMI)
– Allows remote method calls
• Objects in different programs can communicate
• Method calls appear same as those in same program
– Based on Remote Procedure Calls (RPC)
• Developed in 1980's
• Allows procedural program (like C) to call function on another
computer
• Performs networking and marshalling of data (packaging
arguments and return values)
• Not compatible with objects
• Interface Definition Language required - describe functions
– RMI is Java's implementation of RPC
Introduction to RMI
• 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
3
Interface Remote in java.rmi
import java.rmi.*;
4
5
public interface TemperatureServer extends Remote {
6
public WeatherInfo[] getWeatherInfo()
7
8
1. import
throws RemoteException;
1.1 extends Remote
}
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
• Subclass constructors must throw RemoteExceptions
37
38
URL url = new URL(
"http://iwin.nws.noaa.gov/iwin/us/traveler.html" );
– URL object
• Contains URL for Traveler's Forecast web page
• Throws MalformedURLException
Implementing the Remote Interface
40
41
42
BufferedReader in =
new BufferedReader(
new InputStreamReader( url.openStream() ) );
– Open connection to file specified by URL
– Method openStream (class URL)
• Opens network connection using Http protocol
• If successful, InputStream object returned (else
IOException)
– InputStreamReader
• Translates bytes to Unicode characters
– BufferedReader
• Buffers characters
• Method readLine
– Returns one line as a String
Implementing the Remote Interface
44
String separator = "</PRE><HR> <BR><PRE>";
47
48
while ( !in.readLine().startsWith( separator ) )
;
// do nothing
– Sentinel String to find relevant part of HTML code
• readLine until sentinel found
51
52
String s1 =
"CITY
WEA
HI/LO
WEA
HI/LO";
– A string used as column head
• Second "WEA
HI/LO" is for next day, we do not use
– Locate column head and get first city's info
66
inputLine = in.readLine();
// get first city's info
Implementing the Remote Interface
70
71
72
73
75
WeatherInfo w = new WeatherInfo(
inputLine.substring( 0, 16 ),
inputLine.substring( 16, 22 ),
inputLine.substring( 23, 29 ) );
cityVector.addElement( w ); // add to Vector
– WeatherInfo objects
• City name, temperature, description of weather
– Method substring to extract data from line
• Store all WeatherInfo objects in a Vector
84
85
weatherInformation[ i ] =
( WeatherInfo ) cityVector.elementAt( i );
– Store data in WeatherInfo array
• elementAt returns Object (must be cast)
88
in.close();
// close connection to NWS server
– Close connection
Implementing the Remote Interface
116
String serverObjectName = "//localhost/TempServer";
– Name of server object
• Used by clients to connect
• //host:port/remoteObjectName
– host - computer running registry for remote objects
» Where remote object executes
– port - port number of registry on host (1099 default)
– remoteObjectName - client uses to locate object
– Registry managed by rmiregistry (located at host and
port)
• Remote objects register with it, clients use it to locate service
• localhost (same computer)
– Same as IP 127.0.0.1
Implementing the Remote Interface
112
113
116
TemperatureServerImpl temp =
new TemperatureServerImpl();
String serverObjectName = "//localhost/TempServer";
117
Naming.rebind( serverObjectName, temp );
– static method rebind (class Naming)
• Binds object to rmiregistry
• Named //localhost/TempServer
– Name used by client
• rebind replaces any previous objects with same name
– Method bind does not
1
// Fig. 20.1: TemperatureServer.java
2 // TemperatureServer interface definition
3
import java.rmi.*;
4
5
public interface TemperatureServer extends Remote {
6
1. Interface
------------------
public WeatherInfo[] getWeatherInfo()
7
throws RemoteException;
8
}
9
TemperatureServer interface.
1. extends
UnicastRemote
Object, implements
TemperatureServer
10 // Fig. 20.2: TemperatureServerImpl.java
11 // TemperatureServerImpl definition
12 import java.rmi.*;
13 import java.rmi.server.*;
14 import java.util.*;
1.1 Constructor
Allows objects to be exported.
15 import java.io.*;
16 import java.net.*;
17
18 public class TemperatureServerImpl extends UnicastRemoteObject
19
20
implements TemperatureServer {
private WeatherInfo weatherInformation[];
21
22
public TemperatureServerImpl() throws RemoteException
23
{
24
super();
25
updateWeatherConditions();
26
27
}
Superclass constructor exports objects, and
this constructor must be able to throw
RemoteException.
28
// get weather information from NWS
29
private void updateWeatherConditions()
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
throws RemoteException
{
try {
URL of web site (URL object).
System.err.println(
"Updating weather information..." );
// Traveler's Forecast Web Page
URL url = new URL(
"http://iwin.nws.noaa.gov/iwin/us/traveler.html" );
BufferedReader in =
new BufferedReader(
new InputStreamReader( url.openStream() ) );
2. updateWeather
Conditions
2.1 URL
2.2 BufferedReader
2.3 readLine
String separator = "</PRE><HR> <BR><PRE>";
// locate first horizontal line on WebOpen
pageconnection to file.
while ( !in.readLine().startsWith( separator
) )
InputStreamReader
formats it to Unicode
;
// do nothing
characters, and BufferedReader buffers the
characters.
// s1 is the day format and s2 is the night format
String s1 =
"CITY
WEA
HI/LO
WEA
HI/LO";
readLine
until
separator
String s2 =
"CITY
WEA
LO/HI
WEA
LO/HI";
String inputLine = "";
found.
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// locate header that begins weather information
do {
inputLine = in.readLine();
} while ( !inputLine.equals( s1 ) &&
!inputLine.equals( s2 ) ); Create WeatherInfo
Vector cityVector = new Vector();
inputLine = in.readLine();
object, add data
2.4 Locate
header
(substring), add to Vector.
Loop
until
blank line reached.
2.5 Loop
// get first city's info
while ( !inputLine.equals( "" ) ) {
// create WeatherInfo object for city
WeatherInfo w = new WeatherInfo(
inputLine.substring( 0, 16 ),
inputLine.substring( 16, 22 ),
inputLine.substring( 23, 29 ) );
2.5.1 WeatherInfo
2.5.2 readLine
2.6 WeatherInfo array
cityVector.addElement( w ); // add to Vector
inputLine = in.readLine(); // get next city's info
}
// create array to return to client
weatherInformation =
new WeatherInfo[ cityVector.size() ];
Create WeatherInfo array, cast
Vector elements.
for ( int i = 0; i < weatherInformation.length; i++ )
weatherInformation[ i ] =
( WeatherInfo ) cityVector.elementAt( i );
87
88
System.err.println( "Finished Processing Data." );
in.close(); // close connection to NWS server
89
90
91
92
93
94
95
96
97
98
}
99
100
101
// implementation for TemperatureServer interface method
public WeatherInfo[] getWeatherInfo()
102
103
104
105
106
107
108
109
110
111
112
113
114
}
catch( java.net.ConnectException ce ) {
System.err.println( "Connection failed." );
System.exit( 1 );
}
catch( Exception e ) {
e.printStackTrace();
System.exit( 1 );
}
Return the WeatherInfo array.
{
return weatherInformation;
}
public static void main( String args[] ) throws Exception
{
System.err.println(
"Initializing server: please wait." );
// create server object
TemperatureServerImpl temp =
new TemperatureServerImpl();
2.7 close
3. getWeatherInfo
4. main
4.1 temp
115
// bind TemperatureServerImpl object to the rmiregistry
116
String serverObjectName = "//localhost/TempServer";
117
Naming.rebind( serverObjectName, temp );
118
System.err.println(
119
120
121 }
"The Temperature Server is up and
4.2
running."
);server object. serverObjectName
Name of
}
rebind binds object to
rmiregistry.
4.3 rebind
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/ Fig. 20.3: WeatherInfo.java
// WeatherInfo class definitionThis allows objects
import java.rmi.*;
stream of bytes.
import java.io.Serializable;
to be passed as a
public class WeatherInfo implements Serializable {
private String cityName;
private String temperature;
private String description;
public WeatherInfo( String city, String desc, String temp )
{
cityName = city;
temperature = temp;
description = desc;
}
public String getCityName() { return cityName; }
public String getTemperature() { return temperature; }
public String getDescription() { return description; }
}
1. Class WeatherInfo
implements
Serializable
1. Instance variables
1.1 Constructor
2. Get methods
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
26
private void getRemoteTemp( String ip )
String serverObjectName = "//" + ip + "/TempServer";
– Can specify IP address at command line (more later)
30
31
TemperatureServer mytemp = ( TemperatureServer )
Naming.lookup( serverObjectName );
– static method lookup (class Naming)
– Returns reference to Remote object
• Cast to TemperatureServer
– Reference may be used as normal
• Only difference that copy of array returned
34
WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
Define the client
40
50
51
);
52
53
JPanel p = new JPanel();
for ( int i = 0; i < w.length; i++ ) {
w[ i ] = new WeatherItem( weatherInfo[ i ]
p.add( w[ i ] );
}
– Add WeatherItems
• Initialize with WeatherInfo
68
public static void main( String args[] )
69
{
70
74
75
76
77
TemperatureClient gt = null;
if ( args.length == 0 )
gt = new TemperatureClient( "localhost" );
else
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
19
20
21
22
23
24
25
26
static {
backgroundImage = new ImageIcon( "images/back.jpg" );
weatherImages =
new ImageIcon[ weatherImageNames.length ];
for ( int i = 0; i < weatherImageNames.length; ++i )
weatherImages[ i ] = new ImageIcon(
"images/" + weatherImageNames[ i ] + ".jpg" );
}
Define the client
– Array of descriptions and matching array of images
• weatherConditions and weatherImages
32
public WeatherItem( WeatherInfo w )
35
weatherInfo = w;
38
for ( int i = 0; i < weatherConditions.length;
++i
39 )
if ( weatherConditions[ i ].equals(
40
weatherInfo.getDescription().trim() ) )
{
41
weather = weatherImages[ i ];
– Tests WeatherInfo object, loads proper image
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Fig. 20.4: TemperatureClient.java
// TemperatureClient definition
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.rmi.*;
1. import
public class TemperatureClient extends JFrame
{
public TemperatureClient( String ip )
{
super( "RMI TemperatureClient..." );
getRemoteTemp( ip );
setSize( 625, 567 );
setResizable( false );
show();
}
1.1 Constructor
2. getRemoteTemp
2.1
serverObjectName
Use ip specified at command line.
2.2 Naming.lookup
Lookup remote object in
// obtain weather information from TemperatureServerImpl
registry. Returns Remote
// remote object
private void getRemoteTemp( String ip )
reference, cast to proper
{
type.
try {
// name of remote server object bound to rmi registry
String serverObjectName = "//" + ip + "/TempServer";
// lookup TemperatureServerImpl remote object
// in rmiregistry
TemperatureServer mytemp = ( TemperatureServer )
Naming.lookup( serverObjectName );
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// get weather information from server
WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
WeatherItem w[] =
new WeatherItem[ weatherInfo.length ];
ImageIcon headerImage =
new ImageIcon( "images/header.jpg" );
Call2.3
likegetWeatherInfo
regular method.
2.4 GUI
JPanel p = new JPanel();
// determine number of rows for the GridLayout;
// add 3 to accommodate the two header JLabels
// and balance the columns
p.setLayout(
new GridLayout( ( w.length + 3 ) / 2, 2 ) );
p.add( new JLabel( headerImage ) ); // header 1
p.add( new JLabel( headerImage ) ); // header 2
for ( int i = 0; i < w.length; i++ ) {
w[ i ] = new WeatherItem( weatherInfo[ i ] );
p.add( w[ i ] );
}
getContentPane().add( new JScrollPane( p ),
BorderLayout.CENTER );
}
catch ( java.rmi.ConnectException ce ) {
System.err.println( "Connection to server failed. " +
"Server may be temporarily unavailable." );
}
2.4.1 WeatherItem
62
catch ( Exception e ) {
63
e.printStackTrace();
64
System.exit( 1 );
65
}
}
3. main
68
public static void main( String args[] )
3.1 args[ 0 ]
69
{
66
67
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
77
gt = new TemperatureClient( args[ 0 ] );
78
79
gt.addWindowListener(
80
new WindowAdapter() {
81
public void windowClosing( WindowEvent e )
82
{
83
System.exit( 0 );
84
}
85
}
86
87
88 }
);
}
args[ 0 ] is the first
argument, which should be
the IP address.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// Fig. 20.5: WeatherItem.java
// WeatherItem definition
import java.awt.*;
import javax.swing.*;
1. Class WeatherItem
public class WeatherItem extends JLabel {
private static ImageIcon weatherImages[], backgroundImage;
private final static String weatherConditions[] =
{ "SUNNY", "PTCLDY", "CLOUDY", "MOCLDY", "TSTRMS",
"RAIN", "SNOW", "VRYHOT", "FAIR", "RNSNOW",
"SHWRS", "WINDY", "NOINFO", "MISG" };
private final static String weatherImageNames[] =
{ "sunny", "pcloudy", "mcloudy", "mcloudy", "rain",
"rain", "snow", "vryhot", "fair", "rnsnow",
"showers", "windy", "noinfo", "noinfo" };
1.1 static variables
1.2 Initializer block
1.3 Load ImageIcons
// static initializer block to load weather images
static {
backgroundImage = new ImageIcon( "images/back.jpg" );
weatherImages =
new ImageIcon[ weatherImageNames.length ];
for ( int i = 0; i < weatherImageNames.length; ++i )
weatherImages[ i ] = new ImageIcon(
"images/" + weatherImageNames[ i ] + ".jpg" );
}
// instance variables
private ImageIcon weather;
private WeatherInfo weatherInfo;
Use names in weatherImageNames
array to load ImageIcons.
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public WeatherItem( WeatherInfo w )
{
weather = null;
weatherInfo = w;
2. Constructor
// locate image for city's weather condition
for ( int i = 0; i < weatherConditions.length; ++i )
if ( weatherConditions[ i ].equals(
weatherInfo.getDescription().trim() ) ) {
weather = weatherImages[ i ];
break;
Loop though
}
2.1 Compare
conditions
3. paintComponent
weatherConditions and
compare to getDescription.
3.1 paintIcon
//
//
//
if
pick the "no info" image if either there is no
weather info or no image for the current
weather condition
( weather == null ) {
weather = weatherImages[ weatherImages.length - 1 ];
System.err.println( "No info for: " +
weatherInfo.getDescription() );
}
}
public void paintComponent( Graphics g )
{
super.paintComponent( g );
backgroundImage.paintIcon( this, g, 0, 0 );
Attach background to WeatherItem.
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 );
64
g.drawString( weatherInfo.getTemperature(), 130, 19 );
65
66
67
}
69
// make WeatherItem's preferred size the
70
// the background image
71
public Dimension getPreferredSize()
72
{
73
Draw city name, high/low, and attach
weather
image to
width
and height
of WeatherItem.
return new Dimension( backgroundImage.getIconWidth(),
74
76 }
3.3 paintIcon
weather.paintIcon( this, g, 253, 1 );
68
75
3.2 drawString
backgroundImage.getIconHeight() );
}
Compile and Execute the Server and the
Client
• Build and execute application
– All pieces in place
– Compile classes with javac
– Remote server class (TemperatureServerImpl)
compiled with rmic compiler
• Makes a stub class - allows client to access remote methods
and server to provide its services
• Gets remote method calls, passes to RMI system, which
performs networking
• rmic TemperatureServerImpl
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
• Must bind remote server object
– Run TemperatureServerImpl application
java TemperatureServerImpl
– Superclass UnicastRemoteObject
• Constructor exports remote object
• main binds object to rmiregistry
• rmiregistry provides host and port number to clients
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