注意事項(xiàng)
1.服務(wù)接口要繼承java.rmi.Remote接口田篇,聲明方法必須 throws
java.rmi.RemoteException,否則會(huì)拋異常
2.接口實(shí)現(xiàn)類(lèi)繼承UnicastRemoteObject類(lèi)箍铭,構(gòu)造方法需要throws RemoteException泊柬,同時(shí)將實(shí)現(xiàn)類(lèi)聲明為public
3.實(shí)現(xiàn)類(lèi)最好實(shí)現(xiàn)Serializable接口,實(shí)現(xiàn)方法中throws java.rmi.RemoteException
代碼收藏
======================interface============================
public interface RomTest extends Remote {
String RMI_NAME = "rmi.test.service";
public void say() throws RemoteException;
}
==========================Impl=============================
public class RomTestImpl extends UnicastRemoteObject implements RomTest, Serializable {
protected RomTestImpl() throws RemoteException {
super();
}
@Override
public void say(){
System.out.println("hahha");
}
}
==========================server============================
public class TestServer {
public static void main(String[] args) {
try {
RomTest r = new RomTestImpl();
//注冊(cè)遠(yuǎn)程服務(wù)對(duì)象
Registry registry = LocateRegistry.createRegistry(10002);
try {
try {
Naming.bind("rmi://127.0.0.1:10002/" + RomTest.RMI_NAME, r);
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
==========================client===========================
public class TestClient {
public static void main(String[] args){
try {
RomTest ms = (RomTest) Naming.lookup("rmi://12.128.11.100:10002/"+RomTest.RMI_NAME);
ms.say();
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}