Hello Netty~

1.引入netty包,因为netty5是个失败的产品,已经不提供维护,所以推荐使用netty4

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.25.Final</version>
</dependency>

2.新建HelloServer

/**
 * @Description:实现客户端发送一个请求,服务器返回一个Hello Netty~
 */
public class HelloServer {
    /**
     * 实现客户端发送一个请求,服务器会返回一个Hello Netty~
     */
    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());//子处理器,用于处理workGroup

            //启动server,并且设置8088位启动的端口号,同事启动方式为同步
            ChannelFuture channelFuture = serverBootstrap.bind(8088).sync();
            //监听关闭的channel,设置为同步方式
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

3.新建HelloServerInitializer

/**
 * @Description:初始化器,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("customHandler",new CustomerHandler());
    }
}

4.

/**
 * 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);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值