Distributed development using RMI
Bromon original copyright
RMI is a very important technique in J2EE, which is a remote method call, which is the foundation of EJB (Enterprise Javabean). It is easy to write a distributed application based on pure Java (Pure Java), allowing the performance layer, the logic layer, and the data layer to separate each other, facilitating the management of the program maintenance and data. The following uses RMI to write a simple distributed program to introduce the method of use of RMI. In order to make the program more reference value, we are not limited to implementing a simple example of "Hello, World". We will transmit a more complex object in RMI. Specifically, the server is connected to the MSSQL database after requesting, and reads the data generated a window, displayed on the client. The program involves the RMI, SWING component, JDBC-ODBC Bridge connection database in Java, so readers preferably have some basic knowledge of Java.
First, the development environment
First, you need a JDK. The higher the version, the better J2SDK1.4.1, you can download in java.sun.com; the server side needs to install the MSSQL, the version is preferably 7.0 and more. The client needs to have JRE (Java Run Environment, Java Run Environment), but most operating systems have built-in (except for Windows XP, you need to install plugins, you can download them in java.sun.com), but use new JRE to avoid A lot of inexplicable problems. Although notepad is enough to let us complete all code writing, a good editing tool allows you to be more efficient, recommended using EditPlus 2. Since the JDK installation is not the focus of this question, only simply tell the JDK installation under Windows. Download J2SDK1.4.1 running, all the way next, the default is installed in C: J2SDK1.4.1. Set environment variables for Windows, add them in Path; C: J2SDK 1.4.1in, then create a variable set classpath = C: J2SDK1.4.1Lib OOLS.jar. If your installation directory is customized, you can do it accordingly. Logout once makes the environment variable, open a console window (open the MSDOS window under Win98), enter Java, you can see the Java parameter list, indicating that there is no problem. Create a database and form in MSSQL. Suppose the database name is DB1, the table name is Table1, and a string field name is established, and an record is added arbitrarily. Create a data source for the database, assume that the data source is named DATA. Ready to do this, Let's Go! Second, a complete RMI program includes three parts: main interface, server side, and client. Let's write while writing. The first is to define an interface: //myinterface.java import java.rmi. *; // All RMI programs must introduce the RMI package import javax.swing. *; // Create a package to be introduced by the visual environment
Public class myinterface extends Remote {jframe getData () throws RemoteException;} This interface defines how far-ends can be modified. GetData (), which returns a JFrame, which is a swing window. This method must throw RemoteException exception. Save the file as MyInterface.java. Compile this file under the console: Javac MyInterface.java generates a file of MyInterface.class. Then write the server side: //server.java import java.rmi. *; Import javax.swing. *; Import java.sql. *; // Connect the database IMPORT JAVA.RMI.SERVER.UNICASTREMOTEOBJECT; // Introduced a server-side activation package
public class Server extends UnicastRemoteObject implements myInterface {static JFrame S_window = null; static JTextArea JTA = null; public Server () throws RemoteException {} public static void connect () {try {String url = "jdbc: odbc: data"; Class. forName ( "sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection (url, "sa", ""); Statement stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ( "select * from Table1 "); if (rs.next ()) {jta.append (rs.getstring (1) .trim ());} else {jta.com (" There is no data in the database ");} stmt.close () Conn.close ();} catch (exception se) {system.out.println ("Database connection error");}}} public jframe getData () THROWS RemoteException {s_window = new jframe ("test"); JTA = New Jtextarea ("", 10, 5); connection (); jPanel jp = new jPanel (); jp.add (jta); s_window.getContentPane (). add (jp); return (s_window);} public static void; Main (string args []) {try {s_window s = new s_window (); naming.rebind ("r Mi: /// myinterface ", s);} catch (exception e) {E.GETSTACKTRACE ();}}} The server side first throws the RemoteException exception, and then implement the method we just defined in the primary interface GetData (). Use the naming.rebind () method to register the RMI server and bind to our defined S object, so when we send a request to RMI: // localhost / myinterface, the server will automatically call the S object. Processing request. The file is saved as server.java, compiled it: Javac Server.java generates server.class. Finally, we will write the client, very simple: //client.java packge client import java.rmi. *; Import javax.swing. *;
public class client {static JFrame C_window = null; public static void main (String args []) {try {myInterface mi = (myInterface) Naming.lookup ( "rmi: // localhost / myInterface"); C_window = mi.getData ( );} Catch (exception e) {E.GETSTACKTRACE ();} finally {c_window.setBounds (0, 0, 400, 300); c_window.SetDefaultCloseOperation (jframe.exit_on_close); c_window.show ();}}} The program first defines local definitions A Swing window C_Window, this local object will receive the data of the remote object, display it to the user locally, so that the server side can respond to multiple connections, if this local object is not built, mi.getdata () directly, To display the window, the program can run, but the server side will only respond to the last connection connection. Naming.lookup () is used to find the RMI service of the specified address, run the server-side program by calling its getData () method.
The file is saved as client.java, compiled it: Javac Client.java
The program is written, let us deploy it. To the console, switch to the program where the program is located, run the RMIC Server, generate two files: server_stub.class and server_skel.class. Please note that server_stub.class is a copy of the RMI service on the local machine, called the residual root, the client is connected to the server, so you need to install all the .class files below the Client to the client. Server_skel.class is responsible for waiting for the server, called a frame, which connects the server to server_stub.class, and installs all the .class files below the Server to the server side. JDK1.2 The above version has built-in framework, and does not need to be generated, but we need to compatibility with low version of JDK. After the deployment, register now RMI service: Run Start RMIRGISTRY under the console, do not turn off the pop-up window; run the Start Java Server Start the server side, do not turn off the pop-up window, then run the Java Client Start the client, if you will create a swings window With a text area, the content read from the database will be displayed.
Without the development of the RMI development distributed program, there are many advantages, and the multi-layer structure of the program can be realized, and the program is safe, even if the client program is refurbished, it will not cause leakage. RMI is not high on server requirements, as long as you can run Java, you need another installation container like EJB. The program is flexible, and you can provide any needs in the server side according to your own needs without considering the issue. Easy to manage and maintain, just make changes to the server to change the interface and functionality of the client. The extensibility is very strong, using the server-side I / O operation to implement simple web services, using the server-side with other machines to make a simple proxy server, and so on.