一、概念

  • 一个非阻塞的客户端—服务端网络通讯框架
  • 基于异步事件驱动模型
  • 简化Java的TCP和UDP编程
  • 支持HTTP/2,SSL等多种协议
  • 支持多种数据格式,如JSON等
  • 关键技术
    • 通道Channel(数据交换)
      • ServerSocketChannel/NioServerSocketChannel/….
      • SocketChannel/NioSocketChannel
    • 事件EventLoop
      • 为每个通道定义一个EventLoop,处理所有I/O事件
      • EventLoop注册事件
      • EventLoop将事件派发给ChannelHandler
      • EventLoop安排进一步操作
    • 事件
      • 事件按照数据流向进行分类
      • 入站事件:连接激活/数据读取。。。。
      • 出站事件:打开到远程连接/写数据。。。。
    • 事件处理ChannelHandler
      • Channel通道发生数据或状态改变
      • EventLoop会将事件分类,并调用ChannelHandler的回调函数
      • 程序员需要实现ChannelHandler内的回调函数
      • ChannelInboundHandler/ChannelOutboundHandler
    • ChannelHandler工作模式:责任链
      • 责任链模式
        • 将请求的接受者连成一条链
        • 在链上传递请求,直到有一个接收者处理该请求
        • 避免请求者和接收者耦合
      • ChannelHandler 可以有多个,依次进行调用
      • ChannelPipline作为容器,承载多个ChannelHandler
    • ByteBuf
      • 强大的字节容器,提供丰富API进行操作

二、实战

服务端-main

  1. package netty1;
  2. import io.netty.bootstrap.ServerBootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioServerSocketChannel;
  9. import java.net.InetSocketAddress;
  10. public class EchoServer {
  11. public static void main(String[] args) throws InterruptedException {
  12. int port = 8080;
  13. final EchoServerHandler serverHandler = new EchoServerHandler();
  14. EventLoopGroup group = new NioEventLoopGroup();
  15. try{
  16. // ServerBootstrap是Netty中的一个服务器引导类
  17. ServerBootstrap b = new ServerBootstrap();
  18. b.group(group)
  19. .channel(NioServerSocketChannel.class)//设置通道类型
  20. .localAddress(new InetSocketAddress(port))//设置监听端口
  21. .childHandler(new ChannelInitializer<SocketChannel>() {//
  22. @Override
  23. public void initChannel(SocketChannel ch)
  24. {
  25. ch.pipeline().addLast(serverHandler);//添加处理类
  26. }
  27. });
  28. ChannelFuture f = b.bind().sync();//开启监听
  29. if (f.isSuccess())
  30. {
  31. System.out.println(EchoServer.class.getName()+
  32. " started and listening for connections on "+f.channel().localAddress());
  33. }
  34. f.channel().closeFuture().sync();
  35. }finally {
  36. group.shutdownGracefully().sync();
  37. }
  38. }
  39. }

服务端-handler

  1. package netty1;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelFutureListener;
  5. import io.netty.channel.ChannelHandlerContext;
  6. import io.netty.channel.ChannelInboundHandlerAdapter;
  7. import io.netty.util.CharsetUtil;
  8. public class EchoServerHandler extends ChannelInboundHandlerAdapter {
  9. @Override
  10. public void channelRead(ChannelHandlerContext ctx,Object msg)
  11. {
  12. ByteBuf in = (ByteBuf) msg;
  13. String content = in.toString(CharsetUtil.UTF_8);
  14. System.out.println("Server recevied:"+content);
  15. ByteBuf out = ctx.alloc().buffer(1024);
  16. out.writeBytes((content+" 666").getBytes());
  17. ctx.write(out);
  18. }
  19. @Override
  20. public void channelReadComplete(ChannelHandlerContext ctx)
  21. {
  22. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
  23. }
  24. }

客户端-main

  1. package netty1;
  2. import io.netty.bootstrap.Bootstrap;
  3. import io.netty.channel.ChannelFuture;
  4. import io.netty.channel.ChannelInitializer;
  5. import io.netty.channel.EventLoopGroup;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9. import java.net.InetSocketAddress;
  10. public class EchoClient {
  11. public static void main(String[] args) throws InterruptedException {
  12. String host = "localhost";
  13. int port = 8080;
  14. EventLoopGroup group = new NioEventLoopGroup();
  15. try{
  16. Bootstrap b = new Bootstrap();
  17. b.group(group)
  18. .channel(NioSocketChannel.class)
  19. .remoteAddress(new InetSocketAddress(host,port))
  20. .handler(new ChannelInitializer<SocketChannel>() {
  21. @Override
  22. public void initChannel(SocketChannel ch)
  23. {
  24. ch.pipeline().addLast(new EchoClientHandler());
  25. }
  26. });
  27. ChannelFuture f = b.connect().sync();
  28. f.channel().closeFuture().sync();
  29. }finally {
  30. group.shutdownGracefully().sync();
  31. }
  32. }
  33. }

客户端-handler

  1. package netty1;
  2. import io.netty.buffer.ByteBuf;
  3. import io.netty.buffer.Unpooled;
  4. import io.netty.channel.ChannelHandlerContext;
  5. import io.netty.channel.SimpleChannelInboundHandler;
  6. import io.netty.util.CharsetUtil;
  7. public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
  8. @Override
  9. public void channelActive(ChannelHandlerContext ctx)
  10. {
  11. ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
  12. }
  13. @Override
  14. public void channelRead0(ChannelHandlerContext ctx,ByteBuf in)
  15. {
  16. System.out.println("Client received:"+in.toString(CharsetUtil.UTF_8));
  17. }
  18. @Override
  19. public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause)
  20. {
  21. cause.printStackTrace();
  22. ctx.close();
  23. }
  24. }

执行结果

  1. 先执行服务端,服务端打印
  2. netty1.EchoServer started and listening for connections on /0:0:0:0:0:0:0:0:8080
  3. 再执行客户端,客户端打印
  4. Client received:Netty rocks! 666
  5. 服务端打印
  6. Server recevied:Netty rocks!