Netty——(4)Echo服务编写

1.什么是Echo服务和快速创建Netty项目

      1)什么是Echo服务:就是一个应答服务(回显服务器),客户端发送什么数据,服务端就响应的对应的数据

      是一个非常有的用于调试和检测的服务(压测、检查服务是否存活)

(client端也可以进行Handler处理)

       2)IDEA + Maven + jdk8

       netty依赖包  ( 查找方式netty maven)

      3) maven地址:https://mvnrepository.com/artifact/io.netty/netty-all/4.1.32.Final

 

2.Echo服务-服务端程序编写

1)创建maven项目引入maven的依赖

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

2)创建server

public class EchoServer {
    //创建构造方法
    private int port;
    public EchoServer(int port){
        this.port=port;
    }

    public static void main(String[] args) throws InterruptedException {
       //如果之前有端口号用原理的
        int port=8080;
        if (args.length>0){
            port=Integer.getInteger(args[0]);
        }
        new EchoServer(port).run();
    }
/**
 *
 * 功能描述: 启动方法前台多个服务  处理多个线程
 *
 * @param:
 * @return:
 * @auther: LiGang
 * @date: 2019/3/26 11:31
 */
    /**
     * 启动流程
     */
    private void run() throws InterruptedException {
        //配置服务端线程组
        EventLoopGroup bossGroup=new NioEventLoopGroup();
        EventLoopGroup workGroup=new NioEventLoopGroup();

   try{
       //引导整个server的启动
       ServerBootstrap serverBootstrap = new ServerBootstrap();
       serverBootstrap.group(bossGroup,workGroup)
               .channel(NioServerSocketChannel.class)    //指定处理的连接类型
               .childHandler(new ChannelInitializer<SocketChannel>() {
                   @Override
                   protected void initChannel(SocketChannel socketChannel) throws Exception {
                       socketChannel.pipeline().addLast(new EchoServerHandler());
                   }
               });
       System.out.println("Echo 服务器启动ing");
       //绑定端口,同步等待成功
       ChannelFuture cf = serverBootstrap.bind(port).sync();
       System.out.println("ok");
       // 等待服务端监听端口关闭
        cf.channel().closeFuture().sync();


   }finally {
       //优雅的退出
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
   }
    }
}

 

3)创建handler

public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf data = (ByteBuf) msg;
        System.out.println("收到的信息为:"+data.toString(CharsetUtil.UTF_8));
       // ctx.writeAndFlush(msg);
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("111");
        System.out.println("EchoServerHandle channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();

    }
}

 

 

3.Echo服务-客户端程序编写

 

public class EchoClient {
    private  String host;
    private int port;
    public EchoClient(String host,int port){
        this.port=port;
        this.host=host;
    }

    public static void main(String[] args) throws InterruptedException {
        new EchoClient("127.0.0.1",8080).start();
    }

    private void start() throws InterruptedException {
        EventLoopGroup loopGroup = new NioEventLoopGroup();
      try{
          Bootstrap bootstrap = new Bootstrap();
          bootstrap.group(loopGroup)
                  .channel(NioSocketChannel.class)
                  .remoteAddress(new InetSocketAddress(host, port))
                  .handler(new ChannelInitializer<SocketChannel>() {
                      @Override
                      protected void initChannel(SocketChannel socketChannel) throws Exception {
                          socketChannel.pipeline().addLast(new EchoClientHandler());
                      }
                  });
          //连接到服务端,connect是异步连接,调用sync同步等待连接成功
          ChannelFuture channelFuture = bootstrap.connect().sync();

          //阻塞直到客户端通道关闭
          channelFuture.channel().closeFuture().sync();
      }finally {
          loopGroup.shutdownGracefully();
      }

    }


}

handler

public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("EchoClient :receive"+byteBuf.toString(CharsetUtil.UTF_8));

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        ctx.writeAndFlush("read complete");
        System.out.println("client read ok");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client is sign in ");
        ctx.writeAndFlush(Unpooled.copiedBuffer("哈哈",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}

 

4.Echo服务演示和整个流程分析

     1)EventLoop和EventLoopGroup     (相当线程线程组)

     2) Bootstrapt启动引导类

     3)Channel 生命周期,状态变化        (handler中有好多方法)

     4)ChannelHandler和ChannelPipline    channel中的数据经过handler进行处理

 

ChannelPipline   类似工厂的流水线,每个工人就是一个handler处理不同的功能

每个管道可以加多个handler

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

智达教育‍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值