簡體   English   中英

如何在Netty channelRead()上讀寫

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

我正在運行Netty,我需要從客戶端讀取一些消息。 然后,我需要在服務器中執行一些操作,然后向客戶端發送響應。 客戶端可能需要再次回答服務器。 我認為所有這些都必須在同一線程中發生。 如何在Netty服務器中執行此操作? 我使用Telnet測試下面的代碼,但我無法從服務器獲得響應。 如果我注釋第一個塊((讀取消息塊)),那么我開始在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