简体   繁体   中英

How to read and write on Netty channelRead()

Im running Netty and i need to read some messages from the client. 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? Im testing the code below using Telnet but i cant get a response from the server. If i Comment the first block, (Read message block), so i start to receive the response in the Telnet console.

@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)将任何内容写入客户端

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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