使用netty编写第一个hello netty 服务器

构建hello服务器

public class HelloServer{
      public static void main(String[] args) throws Exception {
           
           // 定义一对线程组
           // 主线程组,用于接收客户端连接,但是不做任何处理,像老板一样,不做事
           EventLoopGroup bossGroup = new NioEventLoopGroup();
           // 从线程组,干活的
           EventLoopGroup workerGroup = new NioEventLoopGroup();
           
           try {
                 // netty服务器的创建,ServerBootstrap是一个启动类
                 ServerBootstrap serverBootstrap = new ServerBootstrap();

                 serverBootstrap.group(bossGroup, workerGroup)                   //设置主从线程组

                                       .channel(NioServerSocketChannel.class)   //设置nio的双向通道

                                       .childHandler(new HelloServerInitializer());//子处理器,用于处理workerGroup
                 
                 // 启动server,并且设置8088为启动端口号,同时启动方式为同步
                 ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
                 
                 // 监听关闭的channel,设置为同步方式
                 channelFuture.channel().closeFuture().sync();
           } finally {
                 bossGroup.shutdownGracefully();
                 workerGroup.shutdownGracefully();
           }
      }

}

 

设置channel初始化器

public class HelloServerInitializer extends ChannelInitializer<SocketChannel> {
      @Override
      protected void initChannel(SocketChannel channel) throws Exception {
           // 通过SocketChannel去获得对应的管道
           ChannelPipeline pipeline = channel.pipeline();
           
           // 通过管道,添加handler
           // HttpServerCodec是由Netty自己提供的助手类,可以理解为拦截器
           // 当请求到服务端,我们需要做解码,响应到客户端做编码
           pipeline.addLast("HttpServerCodec",new HttpServerCodec());
           
           // 添加自定义的助手类,返回“hello netty~”

           pipeline.addLast("customerHandler", new CustomerHandler());
      }

}

 

编写自定义助手类

// SimpleChannelInboundHandler:对于请求来讲,相当于[入站,入境]

public class CustomerHandler extends SimpleChannelInboundHandler<HttpObject>{
      @Override
      protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                 throws Exception {
           // 获取channel
           Channel channel = ctx.channel();
           
           if(msg instanceof HttpRequest) {
                 // 显示客户端的远程地址
                 System.out.println(channel.remoteAddress());
                 
                 // 定义发送的数据消息
                 ByteBuf content = Unpooled.copiedBuffer("Hello Netty~", CharsetUtil.UTF_8);
                 
                 // 构建一个http response
                 FullHttpResponse response =
                            new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                                       HttpResponseStatus.OK,
                                       content);
                 // 为响应增加数据类型和长度
                 response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                 response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes());
                 
                 // 把响应刷到客户端
                 ctx.writeAndFlush(response);
           }
      }

}

 

运行结果:

 

posted @ 2020-09-22 18:11  Edward_han  阅读(131)  评论(0编辑  收藏  举报