这跟着官网学Netty
附上官网地址
Netty官网:https://netty.io/wiki/user-guide-for-4.x.html#wiki-h3-4
写一个Discard Server
跟着官方入门文档写一个比"hello,world"还简单的Netty服务端(收到请求后直接丢弃,hello-wordl都省了),边敲边理解。
public class DiscardServer {
private int port;
public DiscardServer(int port) {
this.port = port;
}
public void run() throws Exception {
//接收连接
EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
//处理boss接收并且register到当前worker的连接
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//帮助类,启动Server
ServerBootstrap b = new ServerBootstrap(); // (2)
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) // (3)即将被实例化的ServerChannel,接收连接的类
.childHandler(new ChannelInitializer<SocketChannel>() { // (4)通过给pipeline增加handler来配置Channel的处理逻辑
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new DiscardServerHandler());
}
})
.option(ChannelOption.SO_BACKLOG, 128) // (5)ServerChannel相关参数
.childOption(ChannelOption.SO_KEEPALIVE, true); // (6)被ServerChannel接收的Channel的相关参数
//bind()方法会create a new channel and bind it
//sync()方法会阻塞到future完成,如果失败了会抛出异常
ChannelFuture f = b.bind(port).sync(); // (7)绑定端口,开始接收连接
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception {
int port = 8080;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
}
new DiscardServer(port).run();
}
}
一个简单的Handler
收到请求后,直接释放
public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
((ByteBuf) msg).release();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}