2024-08-01 18:03:21 +08:00
|
|
|
package com.jsowell.pile.rpc;
|
2024-07-31 16:48:29 +08:00
|
|
|
|
|
|
|
|
import io.netty.bootstrap.ServerBootstrap;
|
|
|
|
|
import io.netty.channel.*;
|
|
|
|
|
import io.netty.channel.nio.NioEventLoopGroup;
|
|
|
|
|
import io.netty.channel.socket.nio.NioServerSocketChannel;
|
|
|
|
|
|
|
|
|
|
public class RpcServer {
|
|
|
|
|
|
|
|
|
|
public void bind(Integer port) {
|
|
|
|
|
|
|
|
|
|
EventLoopGroup parent = new NioEventLoopGroup();
|
|
|
|
|
EventLoopGroup child = new NioEventLoopGroup();
|
|
|
|
|
Channel channel = null;
|
|
|
|
|
|
|
|
|
|
try{
|
|
|
|
|
ServerBootstrap serverBootstrap = new ServerBootstrap();
|
|
|
|
|
|
|
|
|
|
serverBootstrap.group(parent, child)
|
|
|
|
|
.channel(NioServerSocketChannel.class)
|
|
|
|
|
.option(ChannelOption.SO_BACKLOG, 1024)
|
|
|
|
|
.childHandler(new ServerChannelInitializer());
|
|
|
|
|
|
|
|
|
|
ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
|
|
|
|
|
|
|
|
|
|
System.out.println("server启动");
|
|
|
|
|
|
|
|
|
|
// 非阻塞等待关闭
|
|
|
|
|
channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
|
|
|
|
|
@Override
|
|
|
|
|
public void operationComplete(ChannelFuture channelFuture) throws Exception {
|
|
|
|
|
System.out.println("server关闭");
|
|
|
|
|
parent.shutdownGracefully();
|
|
|
|
|
child.shutdownGracefully();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
channel = channelFuture.channel();
|
|
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
|
|
|
|
|
|
|
|
|
e.printStackTrace();
|
|
|
|
|
|
|
|
|
|
if(channel == null || !channel.isActive()) {
|
|
|
|
|
System.out.println("server关闭");
|
|
|
|
|
parent.shutdownGracefully();
|
|
|
|
|
child.shutdownGracefully();
|
|
|
|
|
} else {
|
|
|
|
|
channel.close();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
}
|