先定义接口
public interface IHelloService {
public String sayHello(String name);
}
实现类
public class HelloServiceImpl implements IHelloService{
@Override
public String sayHello(String name) {
if(name == null || name.length() == 0 || "null".equalsIgnoreCase(name)){
return "Hello World!";
}
return String.format("%s says: hello!", name);
}
}
服务提供者
public class Provider {
private static Map<String,Object> services = new HashMap<String,Object>(){
private static final long serialVersionUID = 1L;
{put("IHelloService", new HelloServiceImpl());}
};
@SuppressWarnings("resource")
public static void main(String[] args){
try {
ServerSocket server = new ServerSocket(1234);
Socket socket = null;
System.out.println("RPC服务已启动……");
while (true) {
socket = server.accept();
//读取服务信息
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
//接口名称 读取在已使用UTF-8修改版格式编码的字符串
String className = in.readUTF();
//方法名称
String methodname = in.readUTF();
//反射对象参数类型
Class<?>[] parameterTypes = (Class<?>[]) in.readObject();
//读取参数数组
Object[] arguments = (Object[]) in.readObject();
/**
* 执行调用
*/
Object service = services.get(className);//得到服务对象
Method method = service.getClass().getMethod(methodname, parameterTypes);//获得调用方法
Object result = method.invoke(service, arguments);
/**
* 序列化响应
*/
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeObject(result);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
服务消费者
public class Consumer {
@SuppressWarnings("resource")
public static void main(String[] args) {
try {
//接口名称
String className = IHelloService.class.getSimpleName();
//执行方法
Method method = IHelloService.class.getMethod("sayHello", java.lang.String.class);
//传递的参数
Object[] arguments = {"张三"};
/**
* 远程连接调用
*/
Socket socket = new Socket("127.0.0.1", 1234);
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
out.writeUTF(className);//接口名称
out.writeUTF(method.getName());//方法名称
out.writeObject(method.getParameterTypes());//方法参数类型
out.writeObject(arguments);//方法参数
//从远端获取执行结果
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Object result = in.readObject();
System.out.println("执行结果:"+result);
} catch (Exception e) {
e.printStackTrace();
}
}
}