Download presentation
Presentation is loading. Please wait.
1
Remote Method Invocation (RMI)
2
Client-Server Communication
Sockets Remote Procedure Calls Remote Method Invocation (Java)
3
Sockets A socket is defined as an endpoint for communication.
Concatenation of IP address and port The socket :1625 refers to port 1625 on host 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.
4
Socket Communication
5
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 most-significant (big-endian), least-significant(little-endian)
6
Execution of RPC
7
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.
8
Marshalling Parameters
9
Remote Method Invocation
RMI and RPC differs in two ways: 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. 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.
10
Remote Method Invocation (RMI)
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
11
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
12
Case Study: Creating a Distributed System with RMI
RMI example Downloads weather information from National Weather Service website 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
13
Case Study: Creating a Distributed System with RMI
14
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
15
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
16
Defining the Remote Interface
Interface TemperatureServer Extends Remote Describes method getWeatherInfo
17
Interface Remote in java.rmi 1. import 1.1 extends Remote
1 // Fig. 20.1: TemperatureServer.java 2 // TemperatureServer interface definition 3 import java.rmi.*; 4 5 public interface TemperatureServer extends Remote { 6 public WeatherInfo[] getWeatherInfo() throws RemoteException; 8 } Interface Remote in java.rmi 1. import 1.1 extends Remote 2. getWeatherInfo 2.1 throws RemoteException Methods in Remote interface (is a relationship) must be able to throw a RemoteException.
18
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
19
Implementing the Remote Interface
18 public class TemperatureServerImpl extends UnicastRemoteObject implements TemperatureServer { UnicastRemoteObject Provides functionality for remote objects Constructor exports object so it can receive remote calls Wait for client on anonymous port number Subclass constructors must throw RemoteExceptions URL object Contains URL for Traveler's Forecast web page Throws MalformedURLException 22 public TemperatureServerImpl() throws RemoteException URL url = new URL( " );
20
Implementing the Remote Interface
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 BufferedReader in = new BufferedReader( new InputStreamReader( url.openStream() ) );
21
Implementing the Remote Interface
String separator = "</PRE><HR> <BR><PRE>"; while ( !in.readLine().startsWith( separator ) ) ; // do nothing Sentinel String to find relevant part of HTML code readLine until sentinel found 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 String s1 = "CITY WEA HI/LO WEA HI/LO"; inputLine = in.readLine(); // get first city's info
22
Implementing the Remote Interface
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 Store data in WeatherInfo array elementAt returns Object (must be cast) Close connection weatherInformation[ i ] = ( WeatherInfo ) cityVector.elementAt( i ); in.close(); // close connection to NWS server
23
Implementing the Remote Interface
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
24
Implementing the Remote Interface
Naming.rebind( serverObjectName, temp ); TemperatureServerImpl temp = new TemperatureServerImpl(); String serverObjectName = "//localhost/TempServer"; 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
25
1. extends UnicastRemote Object, implements TemperatureServer
1 // Fig. 20.1: TemperatureServer.java 2 // TemperatureServer interface definition 3 import java.rmi.*; 1. Interface 1. extends UnicastRemote Object, implements TemperatureServer 1.1 Constructor 4 5 public interface TemperatureServer extends Remote { 6 public WeatherInfo[] getWeatherInfo() throws RemoteException; 8 } 9 TemperatureServer interface. 10 // Fig. 20.2: TemperatureServerImpl.java 11 // TemperatureServerImpl definition 12 import java.rmi.*; 13 import java.rmi.server.*; Allows objects to be exported. 14 import java.util.*; 15 import java.io.*; 16 import java.net.*; 17 18 public class TemperatureServerImpl extends UnicastRemoteObject implements TemperatureServer { 20 private WeatherInfo weatherInformation[]; 21 22 public TemperatureServerImpl() throws RemoteException 23 { Superclass constructor exports objects, and this constructor must be able to throw RemoteException. super(); updateWeatherConditions(); 26 } 27
26
2. updateWeather Conditions 2.1 URL 2.2 BufferedReader 2.3 readLine
28 // get weather information from NWS 29 private void updateWeatherConditions() throws RemoteException 31 { try { System.err.println( 2. updateWeather Conditions 2.1 URL 2.2 BufferedReader 2.3 readLine URL of web site (URL object). "Updating weather information..." ); 35 // Traveler's Forecast Web Page URL url = new URL( " ); 39 BufferedReader in = new BufferedReader( new InputStreamReader( url.openStream() ) ); 43 Open connection to file. InputStreamReader formats it to Unicode characters, and BufferedReader buffers the characters. String separator = "</PRE><HR> <BR><PRE>"; 45 // locate first horizontal line on Web page while ( !in.readLine().startsWith( separator ) ) ; // do nothing readLine until separator found. 49 // s1 is the day format and s2 is the night format String s1 = "CITY WEA HI/LO WEA HI/LO"; String s2 = "CITY WEA LO/HI WEA LO/HI"; String inputLine = ""; 56
27
Create WeatherInfo array, cast Vector elements.
// locate header that begins weather information do { inputLine = in.readLine(); } while ( !inputLine.equals( s1 ) && 2.4 Locate header 2.5 Loop 2.5.1 WeatherInfo 2.5.2 readLine 2.6 WeatherInfo array Create WeatherInfo object, add data (substring), add to Vector. Loop until blank line reached. !inputLine.equals( s2 ) ); 62 63 Vector cityVector = new Vector(); 65 inputLine = in.readLine(); // get first city's info 67 while ( !inputLine.equals( "" ) ) { // create WeatherInfo object for city WeatherInfo w = new WeatherInfo( inputLine.substring( 0, 16 ), inputLine.substring( 16, 22 ), inputLine.substring( 23, 29 ) ); 74 cityVector.addElement( w ); // add to Vector inputLine = in.readLine(); // get next city's info } 78 Create WeatherInfo array, cast Vector elements. // create array to return to client weatherInformation = new WeatherInfo[ cityVector.size() ]; 82 for ( int i = 0; i < weatherInformation.length; i++ ) weatherInformation[ i ] = ( WeatherInfo ) cityVector.elementAt( i ); 86
28
2.7 close 3. getWeatherInfo 4. main 4.1 temp
System.err.println( "Finished Processing Data." ); in.close(); // close connection to NWS server } 2.7 close 3. getWeatherInfo 4. main 4.1 temp 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. 98 } 99 // implementation for TemperatureServer interface method public WeatherInfo[] getWeatherInfo() { return weatherInformation; } 105 public static void main( String args[] ) throws Exception { System.err.println( "Initializing server: please wait." ); 110 // create server object TemperatureServerImpl temp = new TemperatureServerImpl(); 114
29
4.2 serverObjectName 4.3 rebind
// bind TemperatureServerImpl object to the rmiregistry String serverObjectName = "//localhost/TempServer"; Naming.rebind( serverObjectName, temp ); Name of server object. 4.2 serverObjectName 4.3 rebind System.err.println( rebind binds object to rmiregistry. "The Temperature Server is up and running." ); } 121 }
30
This allows objects to be passed as a stream of bytes.
1 / Fig. 20.3: WeatherInfo.java 2 // WeatherInfo class definition 3 import java.rmi.*; 4 import java.io.Serializable; 5 6 public class WeatherInfo implements Serializable { 7 private String cityName; 8 private String temperature; 9 private String description; 10 11 public WeatherInfo( String city, String desc, String temp ) 12 { cityName = city; temperature = temp; description = desc; 16 } 17 18 public String getCityName() { return cityName; } 19 20 public String getTemperature() { return temperature; } 21 22 public String getDescription() { return description; } 23 } This allows objects to be passed as a stream of bytes. 1. Class WeatherInfo implements Serializable 1. Instance variables 1.1 Constructor 2. Get methods
31
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)
32
Define the client Can specify IP address at command line (more later)
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 22 private void getRemoteTemp( String ip ) String serverObjectName = "//" + ip + "/TempServer"; TemperatureServer mytemp = ( TemperatureServer ) Naming.lookup( serverObjectName ); WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
33
Define the client Add WeatherItems main Initialize with WeatherInfo
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 main Passes command line argument (ip) to constructor localhost default 68 public static void main( String args[] ) 69 { TemperatureClient gt = null; if ( args.length == 0 ) gt = new TemperatureClient( "localhost" ); else gt = new TemperatureClient( args[ 0 ] );
34
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 { backgroundImage = new ImageIcon( "images/back.jpg" ); weatherImages = new ImageIcon[ weatherImageNames.length ]; 22 for ( int i = 0; i < weatherImageNames.length; ++i ) weatherImages[ i ] = new ImageIcon( "images/" + weatherImageNames[ i ] + ".jpg" ); 26 }
35
Define the client Array of descriptions and matching array of images
weatherConditions and weatherImages Tests WeatherInfo object, loads proper image weatherInfo = w; for ( int i = 0; i < weatherConditions.length; ++i ) if ( weatherConditions[ i ].equals( weatherInfo.getDescription().trim() ) ) { weather = weatherImages[ i ]; 32 public WeatherItem( WeatherInfo w )
36
Use ip specified at command line.
1 // Fig. 20.4: TemperatureClient.java 2 // TemperatureClient definition 3 import java.awt.*; 1. import 1.1 Constructor 2. getRemoteTemp 2.1 serverObjectName 2.2 Naming.lookup 4 import java.awt.event.*; 5 import javax.swing.*; 6 import java.rmi.*; 7 8 public class TemperatureClient extends JFrame 9 { 10 public TemperatureClient( String ip ) 11 { super( "RMI TemperatureClient..." ); getRemoteTemp( ip ); 14 setSize( 625, 567 ); setResizable( false ); Use ip specified at command line. show(); 18 } 19 Lookup remote object in registry. Returns Remote reference, cast to proper type. 20 // obtain weather information from TemperatureServerImpl 21 // remote object 22 private void getRemoteTemp( String ip ) 23 { try { // name of remote server object bound to rmi registry String serverObjectName = "//" + ip + "/TempServer"; 27 // lookup TemperatureServerImpl remote object // in rmiregistry TemperatureServer mytemp = ( TemperatureServer ) Naming.lookup( serverObjectName );
37
2.3 getWeatherInfo 2.4 GUI 2.4.1 WeatherItem
32 // get weather information from server WeatherInfo weatherInfo[] = mytemp.getWeatherInfo(); 2.3 getWeatherInfo 2.4 GUI 2.4.1 WeatherItem WeatherItem w[] = Call like regular method. new WeatherItem[ weatherInfo.length ]; ImageIcon headerImage = new ImageIcon( "images/header.jpg" ); 39 JPanel p = new JPanel(); 41 // 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 49 for ( int i = 0; i < w.length; i++ ) { w[ i ] = new WeatherItem( weatherInfo[ i ] ); p.add( w[ i ] ); } 54 getContentPane().add( new JScrollPane( p ), BorderLayout.CENTER ); } catch ( java.rmi.ConnectException ce ) { System.err.println( "Connection to server failed. " + "Server may be temporarily unavailable." ); }
38
args[ 0 ] is the first argument, which should be the IP address.
catch ( Exception e ) { e.printStackTrace(); System.exit( 1 ); } 66 } 3. main 3.1 args[ 0 ] 67 68 public static void main( String args[] ) 69 { TemperatureClient gt = null; 71 // if no sever IP address or host name specified, // use "localhost"; otherwise use specified host if ( args.length == 0 ) gt = new TemperatureClient( "localhost" ); args[ 0 ] is the first argument, which should be the IP address. else gt = new TemperatureClient( args[ 0 ] ); 78 gt.addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { System.exit( 0 ); } } ); 87 } 88 }
39
Use names in weatherImageNames array to load ImageIcons.
1 // Fig. 20.5: WeatherItem.java 2 // WeatherItem definition 3 import java.awt.*; 1. Class WeatherItem 1.1 static variables 1.2 Initializer block 1.3 Load ImageIcons 4 import javax.swing.*; 5 6 public class WeatherItem extends JLabel { 7 private static ImageIcon weatherImages[], backgroundImage; 8 private final static String weatherConditions[] = { "SUNNY", "PTCLDY", "CLOUDY", "MOCLDY", "TSTRMS", "RAIN", "SNOW", "VRYHOT", "FAIR", "RNSNOW", "SHWRS", "WINDY", "NOINFO", "MISG" }; 12 private final static String weatherImageNames[] = { "sunny", "pcloudy", "mcloudy", "mcloudy", "rain", "rain", "snow", "vryhot", "fair", "rnsnow", "showers", "windy", "noinfo", "noinfo" }; 16 17 // static initializer block to load weather images 18 static { backgroundImage = new ImageIcon( "images/back.jpg" ); weatherImages = new ImageIcon[ weatherImageNames.length ]; 22 for ( int i = 0; i < weatherImageNames.length; ++i ) weatherImages[ i ] = new ImageIcon( "images/" + weatherImageNames[ i ] + ".jpg" ); 26 } Use names in weatherImageNames array to load ImageIcons. 27 28 // instance variables 29 private ImageIcon weather; 30 private WeatherInfo weatherInfo;
40
2. Constructor 2.1 Compare conditions 3. paintComponent 3.1 paintIcon
31 32 public WeatherItem( WeatherInfo w ) 33 { 2. Constructor 2.1 Compare conditions 3. paintComponent 3.1 paintIcon weather = null; weatherInfo = w; 36 // 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 ]; Loop though weatherConditions and compare to getDescription. break; } 44 // pick the "no info" image if either there is no // weather info or no image for the current // weather condition if ( weather == null ) { weather = weatherImages[ weatherImages.length - 1 ]; System.err.println( "No info for: " + weatherInfo.getDescription() ); } 53 } 54 Attach background to WeatherItem. 55 public void paintComponent( Graphics g ) 56 { super.paintComponent( g ); backgroundImage.paintIcon( this, g, 0, 0 ); 59
41
Draw city name, high/low, and attach weather image to WeatherItem.
67 } 68 69 // make WeatherItem's preferred size the width and height of 70 // the background image 71 public Dimension getPreferredSize() 72 { return new Dimension( backgroundImage.getIconWidth(), backgroundImage.getIconHeight() ); 75 } 76 } Font f = new Font( "SansSerif", Font.BOLD, 12 ); g.setFont( f ); g.setColor( Color.white ); g.drawString( weatherInfo.getCityName(), 10, 19 ); g.drawString( weatherInfo.getTemperature(), 130, 19 ); 65 weather.paintIcon( this, g, 253, 1 ); 3.2 drawString 3.3 paintIcon Draw city name, high/low, and attach weather image to WeatherItem.
42
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
43
Compile and Execute the Server and the Client
Start rmiregistry Type rmiregistry at command window No text in response
44
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
45
Compile and Execute the Server and the Client
Execute TemperatureClient java TemperatureClient If server on different machine, specify IP on command line java TemperatureClient Result on next slide
46
Program Output
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.