简体   繁体   English

如何在Netty channelRead()上读写

[英]How to read and write on Netty channelRead()

Im running Netty and i need to read some messages from the client. 我正在运行Netty,我需要从客户端读取一些消息。 Then i need to execute some actions in the Server, then send a response to the client. 然后,我需要在服务器中执行一些操作,然后向客户端发送响应。 Maybe the Client need to answer again to the server. 客户端可能需要再次回答服务器。 I think all this have to happend in the same Thread. 我认为所有这些都必须在同一线程中发生。 How can i do this in the Netty server? 如何在Netty服务器中执行此操作? Im testing the code below using Telnet but i cant get a response from the server. 我使用Telnet测试下面的代码,但我无法从服务器获得响应。 If i Comment the first block, (Read message block), so i start to receive the response in the Telnet console. 如果我注释第一个块((读取消息块)),那么我开始在Telnet控制台中接收响应。

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) { // (2)

    // Read the message sent from client.
    try{
        ByteBuf in = (ByteBuf) msg;
        try {
            while (in.isReadable()) { // (1)
                System.out.print((char) in.readByte());
                System.out.flush();
            }
        }
        catch(Exception e){
            System.out.println("---------------- Reading Exception ----------------");
            e.printStackTrace();
        }finally{
            //ReferenceCountUtil.release(msg);
        }

        // treat the received message
        if(msg.equals("teste")){
            // do Something...
        }           

        //Answer to the client
        try {
            ctx.write(msg); // (1)
            ctx.flush(); // (2) 
        }
        catch(Exception e){
            System.out.println("---------------- Writing Exception ----------------");
            e.printStackTrace();
        }
    }
    finally {
        //ReferenceCountUtil.release(msg); // (2)
    }       

}

在while循环之后: while (in.isReadable()) {...} ,msg ByteBuf不再可读,因此不会通过ctx.write(msg)将任何内容写入客户端

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM