Netty入门实例 TCP服务

Bertha 。 2022-09-04 05:54 188阅读 0赞

基于Netty开发一个入门程序,主要功能:服务端启动后监听一个端口,客户端启动后会给服务端发送一条消息,服务端收到后通过Handler读取消息,进行处理,读取完通过Handler反馈一条消息给客户端。

服务端:

  1. Server
  2. package com.tech.netty.netty;
  3. import io.netty.bootstrap.ServerBootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.ChannelOption;
  7. import io.netty.channel.nio.NioEventLoopGroup;
  8. import io.netty.channel.socket.SocketChannel;
  9. import io.netty.channel.socket.nio.NioServerSocketChannel;
  10. /**
  11. * @author lw
  12. * @since 2021/8/11
  13. **/
  14. public class NettyServer {
  15. public static void main(String[] args) throws InterruptedException {
  16. //1 创建两个线程组bossGroup workerGroup
  17. //2 bossGroup处理客户端连接请求 workerGroup处理客户端数据读写请求
  18. //3 他们都是事件循环组 默认含有CPU核数*2个事件循环NioEventLoop
  19. NioEventLoopGroup bossGroup = new NioEventLoopGroup();
  20. NioEventLoopGroup workerGroup = new NioEventLoopGroup();
  21. try {
  22. //创建服务器端启动对象,进行参数配置
  23. ServerBootstrap serverBootstrap = new ServerBootstrap();
  24. serverBootstrap.group(bossGroup, workerGroup) //设置两个线程组
  25. .channel(NioServerSocketChannel.class) //设置服务器端通道为NioServerSocketChannel
  26. .option(ChannelOption.SO_BACKLOG, 128) //设置连接队列允许的连接个数
  27. .childOption(ChannelOption.SO_KEEPALIVE, true) //设置连接连接状态为活动连接
  28. .childHandler(new ChannelInitializer<SocketChannel>() { //给workerGroup NioEventLoop通过管道添加处理器
  29. @Override
  30. protected void initChannel(SocketChannel socketChannel) throws Exception {
  31. socketChannel.pipeline().addLast(new NettyServerHandler());
  32. }
  33. });
  34. System.out.println("...服务器 is ready...");
  35. //启动服务器并绑定一个端口
  36. ChannelFuture channelFuture = serverBootstrap.bind(6668).sync();
  37. //对通道的关闭事件进行监听
  38. channelFuture.channel().closeFuture().sync();
  39. } finally {
  40. bossGroup.shutdownGracefully();
  41. workerGroup.shutdownGracefully();
  42. }
  43. }
  44. }
  45. ServerHandler
  46. package com.tech.netty.netty;
  47. import io.netty.buffer.ByteBuf;
  48. import io.netty.buffer.Unpooled;
  49. import io.netty.channel.Channel;
  50. import io.netty.channel.ChannelHandlerContext;
  51. import io.netty.channel.ChannelInboundHandlerAdapter;
  52. import io.netty.channel.ChannelPipeline;
  53. import io.netty.util.CharsetUtil;
  54. /**
  55. * @author lw
  56. * @since 2021/8/11
  57. **/
  58. //自定义一个Handler
  59. public class NettyServerHandler extends ChannelInboundHandlerAdapter {
  60. //读取客户端发送的消息
  61. // ChannelHandlerContext 是一个上下文对象,可以获取通道和管道信息
  62. // msg 是客户端发送的消息
  63. @Override
  64. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  65. System.out.println("服务器读取线程 "+Thread.currentThread().getName());
  66. System.out.println("server ctx:"+ctx);
  67. Channel channel = ctx.channel();
  68. ChannelPipeline pipeline = ctx.pipeline();
  69. ByteBuf byteBuf = (ByteBuf) msg;
  70. System.out.println("客户端发送消息是:"+byteBuf.toString(CharsetUtil.UTF_8));
  71. System.out.println("客户端地址:"+channel.remoteAddress());
  72. }
  73. //数据读取完毕
  74. @Override
  75. public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
  76. //发送数据
  77. ctx.writeAndFlush(Unpooled.copiedBuffer("hello 客户端",CharsetUtil.UTF_8));
  78. }
  79. //处理异常 一般是需要关闭通道
  80. @Override
  81. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  82. ctx.close();
  83. }
  84. }

客户端:

  1. client
  2. package com.tech.netty.netty;
  3. import io.netty.bootstrap.Bootstrap;
  4. import io.netty.channel.ChannelFuture;
  5. import io.netty.channel.ChannelInitializer;
  6. import io.netty.channel.nio.NioEventLoopGroup;
  7. import io.netty.channel.socket.SocketChannel;
  8. import io.netty.channel.socket.nio.NioSocketChannel;
  9. /**
  10. * @author lw
  11. * @since 2021/8/11
  12. **/
  13. public class NettyClient {
  14. public static void main(String[] args) throws InterruptedException {
  15. //客户端需要一个事件循环组
  16. NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
  17. try {
  18. // 创建客户端启动对象 并配置参数
  19. Bootstrap bootstrap = new Bootstrap();
  20. bootstrap.group(eventExecutors) //设置线程组
  21. .channel(NioSocketChannel.class) //设置客户端通道
  22. .handler(new ChannelInitializer<SocketChannel>() { //设置处理器
  23. @Override
  24. protected void initChannel(SocketChannel socketChannel) throws Exception {
  25. socketChannel.pipeline().addLast(new NettyClientHandler());
  26. }
  27. });
  28. System.out.println("...客户端 is ready...");
  29. //连接服务器
  30. ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
  31. //对通道关闭事件进行监听
  32. channelFuture.channel().closeFuture().sync();
  33. } finally {
  34. eventExecutors.shutdownGracefully();
  35. }
  36. }
  37. }
  38. ClientHandler
  39. package com.tech.netty.netty;
  40. import io.netty.buffer.ByteBuf;
  41. import io.netty.buffer.Unpooled;
  42. import io.netty.channel.ChannelHandlerContext;
  43. import io.netty.channel.ChannelInboundHandlerAdapter;
  44. import io.netty.util.CharsetUtil;
  45. /**
  46. * @author lw
  47. * @since 2021/8/11
  48. **/
  49. public class NettyClientHandler extends ChannelInboundHandlerAdapter {
  50. //当通道就绪会触发该方法 给服务器发送数据
  51. @Override
  52. public void channelActive(ChannelHandlerContext ctx) throws Exception {
  53. System.out.println("client ctx:"+ctx);
  54. ctx.writeAndFlush(Unpooled.copiedBuffer("hello 服务器", CharsetUtil.UTF_8));
  55. }
  56. //当通道有读取事件时触发
  57. @Override
  58. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  59. ByteBuf byteBuf = (ByteBuf) msg;
  60. System.out.println("服务器回复的消息:"+byteBuf.toString(CharsetUtil.UTF_8));
  61. System.out.println("服务器的地址:"+ctx.channel().remoteAddress());
  62. }
  63. @Override
  64. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
  65. ctx.close();
  66. }
  67. }

发表评论

表情:
评论列表 (有 0 条评论,188人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Springboot+Netty搭建TCP服务

    Netty是业界最流行的nio框架之一,它具有功能强大、性能优异、可定制性和可扩展性的优点 Netty的优点: 1.API使用简单,开发入门门槛低。 2.功能十分强大,预

    相关 Netty入门实例 TCP服务

    基于Netty开发一个入门程序,主要功能:服务端启动后监听一个端口,客户端启动后会给服务端发送一条消息,服务端收到后通过Handler读取消息,进行处理,读取完通过Handle