知识点:
- Netty框架如何引导服务端监听网络端口并读写消息
- Netty框架如何连接远程服务器并读写消息
- Netty框架ChannelInboundHandlerAdapter部分事件使用方法
- Netty框架Channel管道使用方法
前言
上一篇对Netty框架做了一个大概的介绍,并对核心部件Channel、ChannelHeadler、Future、事件从概念与作用上做了说明,另外还与Java NIO 在编码上做了一个简单的对比,引出了EventLoop。本篇使用一个小示例来了解下Netty框架怎么使用,真正的用起来。
交互图
服务端示例
public static void main(String[] args) throws InterruptedException {
//创建EventLoop
NioEventLoopGroup master = new NioEventLoopGroup();
//创建服务端引导
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(master);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
//指定使用NioServerSocketChannel作为Channel类型
bootstrap.channel(NioServerSocketChannel.class);
//注册一个ChannelInboundHandlerAdapter类型处理channel的连接
bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//在channel的pipeline中加入消息处理类型为ChannelInboundHandlerAdapter
ch.pipeline().addLast(new MessageChannel());
}
});
//使用bind方法启动服务端的监听
ChannelFuture future = bootstrap.bind(30888).sync();
future.channel().closeFuture().sync();
master.shutdownGracefully().sync(