Netty之入门案例

简介: 前面给大家介绍了NIO,我们会发现用NIO实现异步非阻塞的网络通信代码量非常大,而且并不是很好理解,在实际的开发中一般我们也都是会实现基于NIO的框架来操作的,比如Netty,这样开发效率有高而且Bug也少。


 前面给大家介绍了NIO,我们会发现用NIO实现异步非阻塞的网络通信代码量非常大,而且并不是很好理解,在实际的开发中一般我们也都是会实现基于NIO的框架来操作的,比如Netty,这样开发效率有高而且Bug也少。

Netty入门案例

官网:https://netty.io/

环境准备

 你可以去官网下载对应的jar包依赖,然后创建普通的java项目即可,也可以跟着我通过创建maven项目来实现,如下是会用到的依赖

<dependencies>
  <dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>5.0.0.Alpha2</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
  </dependency>
</dependencies>

log4j.properties属性文件

log4j.rootCategory=info, stdout , R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[QC] %p [%t] %C.%M(%L) | %m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=C:\\Tomcat 5.5\\logs\\qc.log
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d-[TS] %p %t %c - %m%n

服务端

TimerServer

package com.dpb.netty.demo;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class TimerServer {
  public void bind(int port) throws Exception{
    // 配置服务端的NIO线程组
    // 服务端接受客户端的连接
    NioEventLoopGroup bossGroup = new NioEventLoopGroup();
    // 进行SocketChannel的网络读写
    NioEventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
      // 用于启动NIO服务端的辅助启动类,目的是降低服务端的开发复杂度
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup,workerGroup)
      // 设置Channel
      .channel(NioServerSocketChannel.class)
      // 设置TCP参数
      .option(ChannelOption.SO_BACKLOG, 1024)
      // 绑定I/O事件的处理类ChildChannelHandler
      .childHandler(new ChildChannelHandler());
    // 绑定端口,同步等待成功
    ChannelFuture f = b.bind(port).sync();
    // 等待服务端监听端口关闭
    f.channel().closeFuture().sync();
    } finally {
      // 优雅退出,释放线程池资源
      bossGroup.shutdownGracefully();
      workerGroup.shutdownGracefully();
    }
  }
  private class ChildChannelHandler extends ChannelInitializer<SocketChannel>{
    @Override
    protected void initChannel(SocketChannel arg0) throws Exception {
      arg0.pipeline().addLast(new TimerServerHandler());
    }
  }
  public static void main(String[] args) throws Exception {
    int port = 8080;
    new TimerServer().bind(port);
  }
}

TimerServerHandler

package com.dpb.netty.demo;
import java.nio.ByteBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
 * 用于对网络事件进行读写操作
 * @author 波波烤鸭
 * @email dengpbs@163.com
 *
 */
public class TimerServerHandler extends ChannelHandlerAdapter{
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    // ByteBuf 类似于NIO中的java.nio.ByteBuffer对象,
    ByteBuf buf = (ByteBuf) msg;
    byte[] req = new byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req,"utf-8");
    System.out.println("The time server receive order : "+body);
    String currentTime = "Query time order".equalsIgnoreCase(body)?new java.util.Date(System.currentTimeMillis()).toString():"BAD ORDER";
    ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
    ctx.write(resp);
  }
  @Override
  public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    // TODO Auto-generated method stub
    ctx.flush();
  }
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // TODO Auto-generated method stub
    ctx.close();
  }
}

客户端

TimeClient

package com.dpb.netty.demo;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
public class TimeClient {
  public static void main(String[] args) throws Exception {
    int port = 8080;
    new TimeClient().connect(port, "127.0.0.1");
  }
  public void connect(int port,String host)throws Exception{
    // 配置客户端NIO线程组
    EventLoopGroup group = new NioEventLoopGroup();
    try{
      Bootstrap b = new Bootstrap();
      b.group(group).channel(NioSocketChannel.class)
        .option(ChannelOption.TCP_NODELAY, true)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel arg0) throws Exception {
            arg0.pipeline().addLast(new TimeClientHandler());
          }
        });
      // 发起异步连接操作
      ChannelFuture f = b.connect(host,port).sync();
      // 等待客户端链路关闭
      f.channel().closeFuture().sync();
    }catch(Exception e){
      e.printStackTrace();
    }finally{
      // 优雅退出,释放NIO线程组
      group.shutdownGracefully();
    }
  }
}

TimeClientHandler

package com.dpb.netty.demo;
import java.util.logging.Logger;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
public class TimeClientHandler extends ChannelHandlerAdapter{
  private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());
  private final ByteBuf firstMessage;
  public TimeClientHandler(){
    byte[] req = "Query time order".getBytes();
    firstMessage = Unpooled.buffer(req.length);
    firstMessage.writeBytes(req);
  }
  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.writeAndFlush(firstMessage);
  }
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    byte[] req  = new  byte[buf.readableBytes()];
    buf.readBytes(req);
    String body = new String(req,"UTF-8");
    System.out.println("Now is :"+body);
  }
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    // TODO Auto-generated method stub
    logger.warning("Unexpected exception from downstream:"+cause.getMessage());
    ctx.close();
  }
}

image.png

测试

 先启动服务器,再启动客户端,输出如下:

服务端

The time server receive order : Query time order

客户端

Now is :Thu Apr 11 22:22:58 CST 2019

总结

 通过案例使用Netty实现了客户端和服务器的通信,可以发现相比传统的NIO程序,Netty的代码更加简洁,开发难度更低,扩展性也更好,非常适合作为基础通信框架被用户集成和使用


相关文章
|
1月前
|
缓存 网络协议 算法
Netty的基础入门(上)
Netty的基础入门(上)
121 0
|
1月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
163 0
|
1月前
|
设计模式 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
109 1
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(一)
|
1月前
|
消息中间件 缓存 Java
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(二)
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
167 1
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(二)
|
10月前
|
消息中间件 编解码 Java
Netty 入门指南
上文《[BIO、NIO、IO多路复用模型详细介绍&Java NIO 网络编程》](https://wangbinguang.blog.csdn.net/article/details/132047951)介绍了几种IO模型以及Java NIO,了解了在网络编程时使用哪种模型可以提高系统性能及效率。即使Java NIO可以帮助开发人员编写和维护网络应用程序,但由于其复杂性以及bug问题,还是诞生很多强大和流行的网络编程框架,比如Netty、Undertow、Grizzly,在平时的开发中大家更倾向于选择这些框架进行开发,而在我们学习和理解网络编程的底层原理时,使用Java NIO可以更加直接和深
53 0
|
1月前
|
消息中间件 缓存 Java
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
118 0
|
1月前
|
缓存 网络协议 算法
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析(二)
《跟闪电侠学Netty》阅读笔记 - Netty入门程序解析
70 1
|
1月前
|
缓存 Java 数据挖掘
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(一)
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty
111 0
《跟闪电侠学Netty》阅读笔记 - 开篇入门Netty(一)
|
1月前
|
前端开发 网络协议 Java
Netty | 工作流程图分析 & 核心组件说明 & 代码案例实践
Netty | 工作流程图分析 & 核心组件说明 & 代码案例实践
140 0
|
1月前
|
JSON 算法 Dubbo
Netty入门实践-模拟IM聊天
本文以入门实践为主,通过原理+代码的方式,实现一个简易IM聊天功能。分为2个部分:Netty的核心概念、IM聊天简易实现。