Netty学习05--Netty5客户端

曾经终败给现在 2023-02-17 12:28 173阅读 0赞

目录结构:

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzMzcxNzY2_size_16_color_FFFFFF_t_70

1.Client

  1. package com.cxb.netty5.client;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. import io.netty.bootstrap.Bootstrap;
  5. import io.netty.channel.Channel;
  6. import io.netty.channel.ChannelFuture;
  7. import io.netty.channel.ChannelInitializer;
  8. import io.netty.channel.EventLoopGroup;
  9. import io.netty.channel.nio.NioEventLoopGroup;
  10. import io.netty.channel.socket.nio.NioSocketChannel;
  11. import io.netty.handler.codec.string.StringDecoder;
  12. import io.netty.handler.codec.string.StringEncoder;
  13. /**
  14. * netty5的客户端
  15. */
  16. public class Client {
  17. public static void main(String[] args) {
  18. //服务类
  19. Bootstrap bootstrap = new Bootstrap();
  20. //worker
  21. EventLoopGroup worker = new NioEventLoopGroup();
  22. try {
  23. //设置线程池
  24. bootstrap.group(worker);
  25. //设置socket工厂、
  26. bootstrap.channel(NioSocketChannel.class);
  27. //设置管道
  28. bootstrap.handler(new ChannelInitializer<Channel>() {
  29. @Override
  30. protected void initChannel(Channel ch) throws Exception {
  31. ch.pipeline().addLast(new StringDecoder());
  32. ch.pipeline().addLast(new StringEncoder());
  33. ch.pipeline().addLast(new ClientHandler());
  34. }
  35. });
  36. ChannelFuture connect = bootstrap.connect("127.0.0.1", 8006);
  37. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  38. while (true) {
  39. System.out.println("请输入:");
  40. String msg = bufferedReader.readLine();
  41. connect.channel().writeAndFlush(msg);
  42. }
  43. } catch (Exception e) {
  44. e.printStackTrace();
  45. } finally {
  46. worker.shutdownGracefully();
  47. }
  48. }
  49. }

2.ClientHandler

  1. package com.cxb.netty5.client;
  2. import io.netty.channel.ChannelHandlerContext;
  3. import io.netty.channel.SimpleChannelInboundHandler;
  4. /**
  5. * 客户端消息处理
  6. */
  7. public class ClientHandler extends SimpleChannelInboundHandler<String> {
  8. @Override
  9. protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
  10. System.out.println("客户端收到消息:"+msg);
  11. }
  12. }

3.MultClient

  1. package com.cxb.netty5.client;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import java.util.concurrent.atomic.AtomicInteger;
  5. import io.netty.bootstrap.Bootstrap;
  6. import io.netty.channel.Channel;
  7. import io.netty.channel.ChannelFuture;
  8. import io.netty.channel.ChannelInitializer;
  9. import io.netty.channel.EventLoopGroup;
  10. import io.netty.channel.nio.NioEventLoopGroup;
  11. import io.netty.channel.socket.nio.NioSocketChannel;
  12. import io.netty.handler.codec.string.StringDecoder;
  13. import io.netty.handler.codec.string.StringEncoder;
  14. /**
  15. * 多连接客户端
  16. */
  17. public class MultClient {
  18. /**
  19. * 服务类
  20. */
  21. private Bootstrap bootstrap = new Bootstrap();
  22. /**
  23. * 会话
  24. */
  25. private List<Channel> channels = new ArrayList<>();
  26. /**
  27. * 引用计数
  28. */
  29. private final AtomicInteger index = new AtomicInteger();
  30. /**
  31. * 初始化
  32. *
  33. * @param count
  34. */
  35. public void init(int count) {
  36. //worker
  37. EventLoopGroup worker = new NioEventLoopGroup();
  38. //设置线程池
  39. bootstrap.group(worker);
  40. //设置socket工厂、
  41. bootstrap.channel(NioSocketChannel.class);
  42. //设置管道
  43. bootstrap.handler(new ChannelInitializer<Channel>() {
  44. @Override
  45. protected void initChannel(Channel ch) throws Exception {
  46. ch.pipeline().addLast(new StringDecoder());
  47. ch.pipeline().addLast(new StringEncoder());
  48. ch.pipeline().addLast(new ClientHandler());
  49. }
  50. });
  51. for (int i = 1; i <= count; i++) {
  52. ChannelFuture future = bootstrap.connect("192.168.3.112", 8006);
  53. channels.add(future.channel());
  54. }
  55. }
  56. /**
  57. * 获取会话
  58. *
  59. * @return
  60. */
  61. public Channel nextChannel() {
  62. return getFirstActiveChannel(0);
  63. }
  64. private Channel getFirstActiveChannel(int count) {
  65. Channel channel = channels.get(Math.abs(index.getAndIncrement() % channels.size()));
  66. if (!channel.isActive()) {
  67. //重连
  68. reconnect(channel);
  69. if (count >= channels.size()) {
  70. throw new RuntimeException("no can use channel");
  71. }
  72. return getFirstActiveChannel(count + 1);
  73. }
  74. return channel;
  75. }
  76. /**
  77. * 重连
  78. *
  79. * @param channel
  80. */
  81. private void reconnect(Channel channel) {
  82. synchronized (channel) {
  83. if (channels.indexOf(channel) == -1) {
  84. return;
  85. }
  86. Channel newChannel = bootstrap.connect("192.168.3.112", 8006).channel();
  87. channels.set(channels.indexOf(channel), newChannel);
  88. }
  89. }
  90. }

4.Start

  1. package com.cxb.netty5.client;
  2. import java.io.BufferedReader;
  3. import java.io.InputStreamReader;
  4. /**
  5. * 启动类
  6. */
  7. public class Start {
  8. public static void main(String[] args) {
  9. MultClient client = new MultClient();
  10. client.init(5);
  11. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  12. while(true){
  13. try {
  14. System.out.println("请输入:");
  15. String msg = bufferedReader.readLine();
  16. client.nextChannel().writeAndFlush(msg);
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }
  22. }

测试,启动服务端,和客户端。

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzMzcxNzY2_size_16_color_FFFFFF_t_70 1

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMzMzcxNzY2_size_16_color_FFFFFF_t_70 2

客户端输入任意字符,服务端收到消息之后,返回hi给客户端。

代码下载​​​​​​​

发表评论

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

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

相关阅读