在写完程序或者写程序之前你要确认你做了如下的事情:
1,已经把你的项目或者说工程的路径加到classpath里面了,不然的话会报
javax.naming.CommunicationException [Root exception is java.rmi.ServerException: RemoteException occurred java.lang.ClassNotFoundException: 类似这种错误哦,解决方式就是在环境变量里面加上 set CLASSPATH=.;D:\Program Files\Genuitec\MyEclipse 8.5\d\Workspaces\MyEclipse 8.5\myTest\bin 2,已经在你所用的java开发环境中比如我的C:\Java\jre6\lib\security 目录下java.policy文件添加一行权限设置 permission java.security.AllPermission "",""; 3,最好把java的命令放到path路径下面 set path=.;C:\Java\jdk1.6.0_20\bin\ 4,这时你就可以start rmiregistry 5,启动服务器程序,可以在eclipse里面run as运行,或者命令行 start java server.Server 6,启动客户程序 命令行 java client.Client OK,下面就列出我的代码 远程接口TestInterfactRemote.java
package server;
import java.rmi.Remote; import java.rmi.RemoteException;
public interface TestInterfactRemote extends Remote{ public String add(String a,String b) throws RemoteException; public String add() throws RemoteException; }
远程接口的实现类TestInterfaceRemoteImpl.java
package server;
import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject;
public class TestInterfaceRemoteImpl extends UnicastRemoteObject implements TestInterfactRemote{ private String name; public TestInterfaceRemoteImpl(String name) throws RemoteException{ this.name = name; } public String add(String a, String b) throws RemoteException { return a+b; } public String add() throws RemoteException { return "Hello Word"; } }
服务器程序Server.java
package server;
import javax.naming.Context; import javax.naming.InitialContext;
public class Server{ public Server() { try { TestInterfactRemote testInterfactRemote = new TestInterfaceRemoteImpl("service1"); Context namingContext = new InitialContext(); namingContext.rebind("rmi://localhost:1099/server", testInterfactRemote); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { new Server(); } }
客户端程序Client.java
package client;
import java.rmi.Naming;
import server.TestInterfactRemote; public class Client { public static void main(String args[]) { try { TestInterfactRemote testInterfactRemote = (TestInterfactRemote) Naming .lookup("rmi://localhost/server"); System.out.println(testInterfactRemote.add("rmi a ", "rmib")); System.out.println(testInterfactRemote.add()); } catch (Exception e) { e.printStackTrace(); } } }
启动客户端程序输出结果如下:
!OK了!!
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/8554499/viewspace-667945/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/8554499/viewspace-667945/