从服务器 netty nio 接收消息 java

Receive message from server netty nio java

我想弄清楚如何使用从 here 找到的 netty nio 服务器和客户端代码创建聊天。我真正想要的是弄清楚我如何准确地使用从客户端和服务器接收到的消息。我在服务器中找到了以下代码,它在服务器中键入了收到的消息:

 public class EchoClientHandler extends ChannelInboundHandlerAdapter {

   public String message;
   @Override
   public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
      System.out.println("Got reply: " + msg.toString().trim());
      message = msg.toString().trim();
      ctx.disconnect();
    }
    // How to store the message variable and use it from my main function?????
 }

此代码代表 echoClient:

public class EchoClient {

  public String host;
  public int port;


  public EchoClient(String host, int port) {

     this.host = host;
     this.port = port;
  }

  public void send(String msg) throws InterruptedException {

      EventLoopGroup eventGroup = new NioEventLoopGroup();

      Bootstrap bootstrap = new Bootstrap();
      bootstrap.group(eventGroup)
            .remoteAddress(host, port)
            .channel(NioSocketChannel.class) // TCP server socket
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(
                            // break stream into "lines"
                            new LineBasedFrameDecoder(EchoServerHandler.LINE_MAX, false, true),
                            new StringDecoder(CharsetUtil.UTF_8),
                            new StringEncoder(CharsetUtil.UTF_8),
                            new EchoClientHandler()
                    );
                }
            });

      ChannelFuture f = bootstrap.connect().sync();
      System.out.println("Connected!");
      f.channel().writeAndFlush(msg).sync();
      System.out.print("Sent: " + msg);
      f.channel().closeFuture().sync();
      eventGroup.shutdownGracefully().sync();
      System.out.println("Done.");
  }

  public static void main(String[] args) throws InterruptedException {

      EchoClientHandler temp = new EchoClientHandler(); //how can i have access to this variable and the returned message?
      String host ="127.0.0.1";
      int port = 8080;
      EchoClient client = new EchoClient(host, port);
      client.send("Hello world!\n");
      temp.message?
  }
}

这里的代码中有一个打印消息,但是Object msg如何与接收到的消息联系起来呢?我想怎样才能使用它?

编辑: public String messagechannelRead 中有一个值但是,在 main 里面是空的。如何正确传递值?猜测 EchoCLientHandler 和 EchoClient 是与我在 EchoClient 中的主要功能不同的线程。但是,有没有办法从我的主要功能中读取从 EchoClientHandler 收到的消息?

您使用 StringEncoder 对传入的 ByteBuf 缓冲区进行编码,StringDecoder 对传出的消息进行解码。您可能想像 BGTaskServerHandler 处理程序中的 bgTaskGroup.submit(new Sleeper(sleepMillis, ctx.channel())); 一样处理它。