java中使用rmi进行远程方法调用 (一)

2014-11-24 11:47:29 · 作者: · 浏览: 19

java中进行远程方法调用,能支持分布式计算。并且可以实现在server的修改,能反应到各个client。

假如server的ip是:192.168.11.2,

server端的代码如下:


[java]
/**
*
*/
package com.vs.rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Product extends Remote {

public String getDescription() throws RemoteException;
}

/**
*
*/
package com.vs.rmi;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Product extends Remote {

public String getDescription() throws RemoteException;
}

[plain]
package com.vs.rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class ProductImpl extends UnicastRemoteObject implements Product {

private String name;

public ProductImpl() throws RemoteException
{
super();
name = "my rmi";
}

@Override
public String getDescription() throws RemoteException {
return "hello world, " + name;
}
}

package com.vs.rmi;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class ProductImpl extends UnicastRemoteObject implements Product {

private String name;

public ProductImpl() throws RemoteException
{
super();
name = "my rmi";
}

@Override
public String getDescription() throws RemoteException {
return "hello world, " + name;
}
}

[java]
/**
*
*/
package com.vs.rmi;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

/**
* @author hadoop
*
*/
public class ProductServer {

/**
* @param args
*/
public static void main(String[] args) {
/*
* 创建和安装一个安全管理器,令其支持 RMI. 作为 Java 开发包的一部分
*
* 适用于 RMI 唯一一个是 RMISecurityManager.
*
*
*
* if(System.getSecurityManager() == null) {
*
* System.setSecurityManager(new RMISecurityManager());
*
* }
*/

try {
LocateRegistry.createRegistry(8808);
ProductImpl server = new ProductImpl();
Naming.rebind("//192.168.11.2:8808/SAMPLE-SERVER", server);
System.out.println("远程对象注册成功, RMI 服务已经启动,等待客户端调用 ....");
} catch (java.net.MalformedURLException me) {
System.out.println("Malformed URL:" + me.toString());
} catch (RemoteException re) {
System.out.println("Remote exception:" + re.toString());
}
}

}

/**
*
*/
package com.vs.rmi;

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;

/**
* @author hadoop
*
*/
public class ProductServer {

/**
* @param args
*/
public static void main(String[] args) {
/*
* 创建和安装一个安全管理器,令其支持 RMI. 作为 Java 开发包的一部分
*
* 适用于 RMI 唯一一个是 RMISecurityManager.
*
*
*
* if(System.getSecurityManager() == null) {
*
* System.setSecurityManager(new RMISecurityManager());
*
* }
*/

try {
LocateRegistry.createRegistry(8808);
ProductImpl server = new ProductImpl();
Naming.rebind("//192.168.11.2:8808/SAMPLE-SERVER", server);
System.out.println("远程对象注册成功, RMI 服务已经启动,等待客户端调用 ....");
} catch (java.net.MalformedURLException me) {
System.out.println("Malformed URL:" + me.toString());
} catch (RemoteException re) {
System.out.println("Remote exception:"