springboot+netty(一)

在这里插入图片描述在这里插入图片描述

实例

helloserver.java

package com.ndd.netty.test;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author ndd
 * @version 2.x实现客户端发一个请求,服务器会返回hello netty
 * @date 2020/3/7 16:45
 */
public class HelloServer {
    public static void main(String[] args) throws InterruptedException {
        //定义一对线程组,主线程组,用于接收客户的连接,但是不做任何处理
        EventLoopGroup mainGroup=new NioEventLoopGroup();
        //从线程组,老板会把线程任务给他
        EventLoopGroup workerGroup=new NioEventLoopGroup();

        try {
            //netty服务器的创建ServerBootstrap是一个启动类
            ServerBootstrap serverBootstrap=new ServerBootstrap();
            serverBootstrap.group(mainGroup,workerGroup) //指定主从模式下的主线程和父线程
                    .channel(NioServerSocketChannel.class) //指定通道的类型 nio双向通道
                    .childHandler(new HelloServerIniaializer());//子处理器,用于处理workerGroup

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

HelloServerIniaializer.java

package com.ndd.netty.test;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpServerCodec;

/**
 * @author ndd
 * @version 2.x 初始化器,channel注册后,会执行里面的相应的执行方法
 * @date 2020/3/7 17:01
 */
public class HelloServerIniaializer extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        //通过channel获得pipeline
        ChannelPipeline pipeline = channel.pipeline();
        //通过pipline添加handler
        //HttpServerCodec是由netty自己提供的助手类,可以理解为拦截器
        //当请求到服务端,我们需要自己编解码,相应到客户端做编码
        pipeline.addLast("HttpServerCodec",new HttpServerCodec());

        //自定义的handler,返回hello netty 相当于自己设置一个拦截器
        pipeline.addLast("CustomServerCodec",new CustomHandler());

    }
}

CustomHandler.java

package com.ndd.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author ndd
 * @version 2.x 创建自定义助手类
 * SimpleChannelInboundHandler 对于请求来讲,相当于[入站]
 * @date 2020/3/7 17:08
 */
public class CustomHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        //获取channel
        Channel channel = channelHandlerContext.channel();
        //显示客户端的消息
        System.out.println(channel.remoteAddress());

        //定义发送的数据消息
        ByteBuf content=Unpooled.copiedBuffer("hello netty~", CharsetUtil.UTF_8);

        //构建一个http response
        DefaultFullHttpResponse defaultFullHttpResponse = //版本号,状态码,内容
                new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,content);
       //为相应增加数据类型和长度
        defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
        defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());

        //把相应刷到客户端 writeAndFlush不仅会写到缓冲区,还会刷新
        channelHandlerContext.writeAndFlush(defaultFullHttpResponse);


    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...注册");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...移出");
        super.channelUnregistered(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...活跃");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...不活跃");
        super.channelInactive(ctx);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...读取完毕");
        super.channelReadComplete(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("用户事件触发。。。");
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel...可写课改");
        super.channelWritabilityChanged(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("助手类添加");
        super.handlerAdded(ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("助手类移出");
        super.handlerRemoved(ctx);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获到异常");
        super.exceptionCaught(ctx, cause);
    }
}

测试

在这里插入图片描述
控制台输出:
在这里插入图片描述助手类是指HttpServerCodec助手类以及我们自己编写的handler(所以有两次的添加和移出)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值