RMI樣本(利用RMI plug-in for Eclipse)

來源:互聯網
上載者:User

RMI樣本

下面以一個例子說明怎麼使用RMI技術。這個例子示範了怎樣將一個檔案上傳到伺服器和怎樣將一個檔案從伺服器上下載下來。

利用RMI for Eclipse外掛程式開發RMI需要以下步驟:

(1)定義和實現遠端介面中的參數

 (2) 定義和實現遠端介面

 (3) 編寫服務端代碼

(4)編寫用戶端代碼 

部署按以下步驟:

(1)點擊Start Local registry

(2)右鍵點擊項目,選擇RMI,點擊Enable Stubs Generation

(3)運行伺服器,run as-->run RMI Application:設定:RMI VM Properties:codebase 選擇compute from classpath

(4)運行用戶端,run as-->run RMI Application:設定:RMI VM Properties:security.policy建立一個即可。

 

下面是範例程式碼:

定義和實現遠端介面中的參數
  (1)定義遠端介面中的參數
  每一個遠端介面中的參數都必須是可序列化的。那麼,如何定義一個序列化的介面呢,簡單,只需從java.io.Serializable繼承即可,如下所示:
  import java.io.Serializable;
  
  public interface FileInformation extends Serializable {
    String getName();
    byte[] getContent();
    void  setInformation(String name , byte[] content);
  };
  (2)實現遠端介面中的參數。
  實現遠端介面中的參數的介面跟與實現其他任何介面沒什麼不一樣的地方,如下所示
   public class FileInformationSev implements FileInformation {

bitsCN全力打造網管學習平台

   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 ;
   }
  } 
  
  那麼,為什麼要序列化遠端介面中的參數(傳回值) ?這是因為需要將用戶端的對象(參數)轉化成byte stream,通過網路通訊協定傳輸到服務端,再還原成服務端的對象進行調用。或者是需要將服務端的對象(傳回值)轉化成byte stream,通過網路通訊協定傳輸到服務端,再還原成用戶端的對象進行調用。
  在 jdk中, java.lang包和java.util包下的類都已經實現了序列化,直接可以用在遠程介面中作參數或傳回值;所有的基本類型也可以直接用在遠程介面中作參數或傳回值;
  
 定義和實現遠端介面
  (1)定義遠端介面
  遠端介面必須從java.rmi.Remote繼承;遠端介面中的方法如果要throw異常,這個異常必須是java.rmi.RemoteException(或java.rmi.RemoteException的子類),否則,這個異常就不能被返回到用戶端。Example如下:

feedom.net關注網管是我們的使命

     
  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)實現遠端介面  
  實現遠端介面比較容易,跟其他介面的實現沒有什麼區別,如下所示:
     
  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國內最早的網管網站
     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{

dl.bitsCN.com網管軟體下載

           input.close();
           input = null ;
         }catch(Exception ex){
         }
        }
      }
      return fileInfo ;
    }
  }
     
  編寫服務端代碼
  服務端代碼主要有3個步驟:
  (1)載入安全管理器
  (2)建立一個服務物件
  (3)將這個服務物件註冊到命名服務上
  :
  import java.rmi.RMISecurityManager;
  import java.rmi.Naming;
  
  public class RMIServer {
   public static void main(String[] args) {
     try{
   //載入安全管理器
        System.setSecurityManager(new RMISecurityManager() );
       
  //建立一個服務物件
        LoadFileService server = new LoadFileService();
        server.setCurrentDir("c://rmiexample");
       
        //將服務物件註冊到rmi註冊伺服器上,而不是其他伺服器
  //(因為LoadFileService extends UnicastRemoteObject)
        Naming.rebind("//127.0.0.1:2000/LoadFileServer", server);

feedom.net關注網管是我們的使命

     }catch(Exception ex){
       System.out.println(ex.getLocalizedMessage());
       ex.printStackTrace();
     }
   }
  }
  
  注意:將對象註冊以後,不可關閉服務物件。

 編寫用戶端代碼
  用戶端代碼需要兩個步驟:
  (1)根據服務的名稱,尋找服務物件
  (2)調用服務服務物件對應的方法完成工作
  在這個例子中,我們從用戶端上傳一個檔案到伺服器,並將伺服器的一個檔案下載下來。
  代碼如下:

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import rmi.common.*;

/*
 *   用戶端代碼需要兩個步驟:
  (1)根據服務的名稱,尋找服務物件
  (2)調用服務服務物件對應的方法完成工作
 */
public class CallLoadTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  try {
//   注意,這裡必須使用介面LoadFile,不能使用他的實作類別LoadFileImpl
   LoadFile 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();
  }
  

 }

}

按照上文部署即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.