RMI example
The following example shows how to use the RMI technology. This example demonstrates how to upload a file to the server and download it from the server.
To develop RMI using the RMI for Eclipse plug-in, follow these steps:
(1) define and implement parameters in the remote interface
(2) define and implement remote interfaces
(3) Write server code
(4) write client code
To deploy an application, follow these steps:
(1) Click Start local registry.
(2) Right-click the project, select RMI, and click Enable stubs generation
(3) run the server, run as --> run rmi application: Set: rmi vm properties: codebase select compute from classpath
(4) run the client, run as --> run rmi application: Set: rmi vm properties: security. policy to create a new one.
The following is the sample code:
Define and implement parameters in remote interfaces
(1) Define parameters in the remote interface
Parameters in each remote interface must be serializable. So, how to define a serialized interface is simple, just inherit from Java. Io. serializable, as shown below:
Import java. Io. serializable;
Public interface fileinformation extends serializable {
String getname ();
Byte [] getcontent ();
Void setinformation (string name, byte [] content );
};
(2) implement parameters in the remote interface.
The interface that implements parameters in the remote interface is nothing different from the interface that implements any other interface, as shown below:
Public class fileinformationsev implements fileinformation {
Bitscn makes every effort to build a network management learning platform
Private string name = NULL;
Private byte [] content = NULL;
Public String getname (){
Return name;
}
Public byte [] getcontent (){
Return content;
}
Public void setinformation (string name, byte [] content ){
This. Name = Name;
This. content = content;
}
}
So why serialize parameters (return values) in the remote interface )? This is because the client object (parameter) needs to be converted to byte stream, transmitted to the server through the network protocol, and then restored to the server object for calling. Or you need to convert the object (return value) of the server to a byte stream, transmit it to the server through the network protocol, and then restore it to the client object for calling.
In JDK, Java. lang Package and Java. classes in the util package have been serialized and can be directly used as parameters or return values in remote interfaces. All basic types can also be directly used as parameters or return values in remote interfaces;
Define and implement remote interfaces
(1) define remote interfaces
The remote interface must be. RMI. remote inheritance; if the method in the remote interface is throw, this exception must be Java. RMI. remoteException (or Java. RMI. remoteException subclass). Otherwise, the exception cannot be returned to the client. Example:
Feedom.net is our mission to focus on Network Management
Import java. RMI. Remote;
Import java. RMI. RemoteException;
Public interface LoadFile extends remote {
Void uploadfile (fileinformation fileinof) throws RemoteException;
Fileinformation downloadfile (string filename) throws RemoteException;
}
2) implement remote interfaces
It is easier to implement a remote interface, which is similar to the implementation of other interfaces, as shown below:
Import java. RMI. Remote;
Import java. RMI. RemoteException;
Import java. Io. ioexception;
Import java. Io. file;
Import java. Io. bufferedinputstream;
Import java. Io. fileinputstream;
Import java. Io. bufferedoutputstream;
Import java. Io. fileoutputstream;
Import java. RMI. server. unicastremoteobject;
Public class loadfileservice extends unicastremoteobject implements LoadFile {
Private string currentdir = NULL;
// This contruction is needed
Public loadfileservice () throws RemoteException {feedom.net was the earliest website administrator in China.
Super ();
}
Public void setcurrentdir (string currentdir ){
This. currentdir = currentdir;
}
Public void uploadfile (fileinformation fileinfo) throws RemoteException {
Bufferedoutputstream output = NULL;
Try {
// Check paramter
If (fileinfo = NULL ){
Throw new RemoteException ("the paramter is null ");
}
// Check filename and content
String filename = fileinfo. getname ();
Byte [] content = fileinfo. getcontent ();
If (filename = NULL | content = NULL ){
Throw new RemoteException ("the file or the content is null ");
}
// Create File
String filepath = This. currentdir + "//" + filename;
File file = new file (filepath );
If (! File. exists ()){
Blog.bitscn.com.
File. createnewfile ();
}
// Save the content to the file
Output = new bufferedoutputstream (New fileoutputstream (File ));
Output. Write (content );
} Catch (RemoteException ex ){
Throw ex;
} Catch (exception ex ){
Throw new RemoteException (ex. getlocalizedmessage ());
} Finally {
If (output! = NULL ){
Try {
Output. Close ();
Output = NULL;
} Catch (exception ex ){
}
}
}
}
Public fileinformation downloadfile (string filename) throws RemoteException {
Fileinformation fileinfo = NULL;
Bufferedinputstream input = NULL;
Try {
// Check paramter
If (filename = NULL ){
Throw new RemoteException ("the paramter is null ");
Blog.bitscn.com.
}
// Get path
String filepath = This. currentdir + "//" + filename;
File file = new file (filepath );
If (! File. exists ()){
Throw new RemoteException ("the file whose name is" + filename + "not existed ");
}
// Get content
Byte [] content = new byte [(INT) file. Length ()];
Input = new bufferedinputstream (New fileinputstream (File ));
Input. Read (content );
// Set file name and content to fileinfo
Fileinfo = new fileinformationsev ();
Fileinfo. setinformation (filename, content );
} Catch (RemoteException ex ){
Throw ex;
} Catch (exception ex ){
Throw new RemoteException (ex. getlocalizedmessage ());
} Finally {
If (input! = NULL ){
Try {
Download the dl.bitscn.com network management software
Input. Close ();
Input = NULL;
} Catch (exception ex ){
}
}
}
Return fileinfo;
}
}
Write server code
The server code consists of three steps:
(1) load the security manager
(2) create a service object
(3) register this service object to the Naming Service.
:
Import java. RMI. rmisecuritymanager;
Import java. RMI. Naming;
Public class rmiserver {
Public static void main (string [] ARGs ){
Try {
// Load the security manager
System. setsecuritymanager (New rmisecuritymanager ());
// Create a service object
Loadfileservice Server = new loadfileservice ();
Server. setcurrentdir ("C: // rmiexample ");
// Register the service object to the RMI registration server, instead of other servers
// (Because loadfileservice extends unicastremoteobject)
Naming. rebind ("/// 127.0.0.1: 2000/loadfileserver", server );
Feedom.net is our mission to focus on Network Management
} Catch (exception ex ){
System. Out. println (ex. getlocalizedmessage ());
Ex. printstacktrace ();
}
}
}
Note: After registering an object, the service object cannot be closed.
Write client code
The client code requires two steps:
(1) Search for the service object based on the service name
(2) Call the method corresponding to the service object to complete the work
In this example, we upload a file from the client to the server and download the file from the server.
The Code is as follows:
Import java.net. malformedurlexception;
Import java. RMI. Naming;
Import java. RMI. notboundexception;
Import java. RMI. RemoteException;
Import RMI. Common .*;
/*
* The client code requires two steps:
(1) Search for the service object based on the service name
(2) Call the method corresponding to the service object to complete the work
*/
Public class callloadtest {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub
Try {
// Note that the interface LoadFile must be used here, and its implementation class loadfileimpl cannot be used.
LoadFile = (LoadFile) Naming. Lookup ("test ");
Fileinformation fileinfo = LoadFile. downloadfile ("sdatlog.txt ");
Byte [] content = fileinfo. getcontent ();
For (byte B: Content)
System. Out. println (B );
// System. Out. println (fileinfo. getcontent (). tostring ());
} Catch (malformedurlexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (RemoteException e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
} Catch (notboundexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
}
}
Follow the preceding steps to deploy the service.