1 Star 0 Fork 0

yclxiao / specialty

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
RpcServer.java 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
yclxiao 提交于 2020-04-14 09:23 . 简易RPC
package com.ycl.blog.simplerpc;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
/**
* User: 杨成龙
* Date: 2020/4/13
* Time: 7:50 下午
* Desc: 类描述
*/
public class RpcServer {
public void export(Object service, int port) throws Exception {
if (service == null) {
throw new IllegalArgumentException("service instance == null");
}
if (port <= 0 || port > 65535) {
throw new IllegalArgumentException("Invalid post " + port);
}
ServerSocket server = new ServerSocket(port);
while (true) {
final Socket socket = server.accept();
new Thread(() -> {
try {
ObjectInputStream input = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
try {
String methodName = input.readUTF();//IO堵塞,获取方法名
Class<?>[] parameterTypes = (Class<?>[]) input.readObject();//IO堵塞,获取参数类型
Object[] arguments = (Object[]) input.readObject();//IO堵塞,取参数
//执行接口方法
Method method = service.getClass().getMethod(methodName, parameterTypes);
Object result = method.invoke(service, arguments);
//将结果写出去
output.writeObject(result);
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
} finally {
output.close();
input.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
}
}
}
Java
1
https://gitee.com/yclxiao/specialty.git
git@gitee.com:yclxiao/specialty.git
yclxiao
specialty
specialty
master

搜索帮助