日期:2014-05-20  浏览次数:20773 次

rmi一个简单的练习: Exception in thread "main" java.lang.ClassCastException: $Proxy0(在线等~~~~~)
5部分组成:
1.IStudent接口
 import java.rmi.Remote;
import java.rmi.RemoteException;

public interface IStudent extends Remote{
public String show(String str)throws RemoteException;
}

2.Student实现类
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class StudentImpl extends UnicastRemoteObject implements IStudent {

public StudentImpl()throws RemoteException{
System.out.println("IStudent");
}

public String show(String str) throws RemoteException {
System.out.println(str);
return str;
}

}

3.服务器端
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
public class Server {

public static void main(String[] args) {
try {
StudentImpl studentImpl = new StudentImpl();
Naming.rebind("rmi://192.168.1.36:1099/studentimpl",studentImpl);

System.out.println("server bind success");
} catch (Exception e) {
e.printStackTrace();


}

}

4.客户端

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

public class Client {

public static void main(String[] args) {
try {
IStudent iStudent = (IStudent)Naming.lookup("studentimpl");//最后运行客户端时,这里报异常无法找到"代理类"
System.out.println(((IStudent) iStudent).show("hello world"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}

}

}

5.IStudent接口的IStudent_stub.class 和 IStudent_skleon.class
还有个策略文件rmi.policy
grant
{
permission java.net.SocketPermission "*:1024-65535","connect";
};

运行:
start rmiregistry 运行成功
java server 运行成功
java client 报异常如下:
  Exception in thread "main" java.lang.ClassCastException: $Proxy0
  at client.Client.main(Client.java:17)
  在线等!~~~~~~~
   


------解决方案--------------------
没实现接口
------解决方案--------------------
可能是你Server端的IStudent的包名和Client端的包名不一致,包名要完全一样