数据传输格式:
客户端调用服务端:
接口简单名/方法名(参数类型权限名:参数值, . ...)
比如 SayHello/sayHello(java.lang.String:lalala)
这里 接口名为SayHello 方法为 sayHello 参数类型为String 内容nana
服务端返回给客户端
返回类型:值
服务端代码:
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
/**
* 它接受的内容是class/方法名(参数类型:参数,参数类型:参数)
*
* @author Administrator
*
*/
public class RPCServer {
private static RPCServer instance = new RPCServer();
private HashMap<String, Object> str_obj = new HashMap<>();
private Selector selector;
private ServerSocketChannel ssc;
private RPCServer() {
try {
ssc = ServerSocketChannel.open();
InetSocketAddress address = new InetSocketAddress(3003);
ssc.configureBlocking(false);
ssc.bind(address);
selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static RPCServer getInstance() {
return instance;
}
public RPCServer addClass(Object obj) {
String name = obj.getClass().getInterfaces()[0].getSimpleName();
str_obj.put(name, obj);
return this;
}
// 开发服务等待连接
public void start() {
System.out.println("-----服务器已经启动了------");
ByteBuffer buff = ByteBuffer.allocate(1024);
try {
while (selector.select() > 0) {
for (SelectionKey sk : selector.selectedKeys()) {
selector.selectedKeys().remove(sk);
if (sk.isAcceptable()) {
// 调用accept方法接受连接,产生服务器端对应的SocketChannel
SocketChannel sc = ssc.accept();
// 设置采用非阻塞模式
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);