1.rmi-demo-api 首先定义基础接口
package com.weizhi.hessian.demo.api;
import java.rmi.Remote;
import java.rmi.RemoteException;
/**
* @ClassName IRpcService
* @Description TODO
* @Author weizhi2018
* @Date 2013-9-27 下午02:58:46
*
*/
public interface IRpcService extends Remote{
public String deal(String data) throws RemoteException;
}
2.rmi-demo-server 发布服务端
继承 UnicastRemoteObject 类,实现服务接口
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import com.weizhi.hessian.demo.api.IRpcService;
public class RpcServiceImpl extends UnicastRemoteObject implements IRpcService {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @throws RemoteException
*/
protected RpcServiceImpl() throws RemoteException {
super();
System.out.println("Sevice Instance.");
}
/*
* @see com.weizhi.hessian.demo.api.IRpcService#deal(java.lang.String)
*/
@Override
public String deal(String data) {
System.out.println("Receive:"+data);
if (data == null || "".equals(data))
return "[Invalid Parameter]";
return "[Tested," + data + "]";
}
}
启动服务
import java.rmi.Naming;
import java.rmi.registry.LocateRegistry;
public class RpcMain {
/**
* @Title main
* @Description TODO
* @Author weizhi2018
* @param args
* @throws
*/
public static void main(String[] args) {
try
{
RpcServiceImpl service = new RpcServiceImpl();
int port = 2099;
LocateRegistry.createRegistry(port);
Naming.rebind("rmi://127.0.0.1:2099/service", service);
System.out.println("Service is running...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.rmi-demo-client 客户端请求
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import com.weizhi.hessian.demo.api.IRpcService;
public class RpcClientMain {
/**
* @Title main
* @Description TODO
* @Author weizhi2018
* @param args
* @throws
*/
public static void main(String[] args) {
try {
IRpcService service1 = (IRpcService) Naming.lookup("rmi://127.0.0.1:2099/service");
String data1 = "weizhi2018-service-1";
String data2 = null;
String result1 = service1.deal(data1);
String result2 = service1.deal(data2);
System.out.println("Send:"+data1+",receive:"+result1);
System.out.println("Send:"+data2+",receive:"+result2);
IRpcService service2 = (IRpcService) Naming.lookup("rmi://127.0.0.1:2099/service");
String data3 = "weizhi2018-service-2";
String data4 = "";
String result3 = service2.deal(data3);
String result4 = service2.deal(data4);
System.out.println("Send:"+data3+",receive:"+result3);
System.out.println("Send:"+data4+",receive:"+result4);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
}