2017-10-18 10 views
1

J'essaie de comprendre comment puis-je créer une conversation en utilisant le serveur netty nio et le code client trouvé à here. Ce que je veux réellement est de comprendre comment exactement je peux utiliser les messages reçus du client et du serveur. J'ai trouvé dans le serveur le code suivant dans le serveur qui tape un message reçu:Recevoir message du serveur netty nio java

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????? 
} 

Ce code signifie la 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? 
    } 
} 

Dans le code ici, il y a un message d'impression, mais Comment le message d'objet peut-il être connecté avec le message reçu? Et comment puis-je l'utiliser quand je veux?

EDIT:public String message dans le channelRead a une valeur cependant, à l'intérieur de la principale est nulle. Comment puis-je transmettre correctement la valeur? Je suppose que EchoCLientHandler et EchoClient sont des threads différents de ma fonction principale dans EchoClient. Cependant, existe-t-il un moyen de lire depuis ma fonction principale le message reçu depuis EchoClientHandler?

Répondre

3

Vous avez utilisé le StringEncoder pour coder le tampon entrant ByteBuf, StringDecoder pour décoder le message sortant. Vous voudrez peut-être traiter avec similaire avec bgTaskGroup.submit(new Sleeper(sleepMillis, ctx.channel())); dans BGTaskServerHandler handler.

+0

Désolé je ne vous suis pas vraiment. Je veux lire le message de ma fonction principale du client. Après la connexion quoi imprimer le message de la main et non de channelRead ou l'analyser dans une nouvelle variable. –

+0

Pourriez-vous élaborer un peu? Avoir mis à jour la question, y compris le client de formulaire de code entier. –

+0

La méthode 'channelRead' et' main' se trouvent dans des threads différents (io asynchrone). Vous pouvez utiliser un type de données intermédiaire pour stocker et extraire de la classe 'EchoClientHandler'. –