標籤:style java 使用 os io 資料 ar cti
1、在沒有任何encoder、decoder的情況下,Netty發送接收資料都是按照ByteBuf的形式,其它形式都是不合法的。
ByteBuf result = (ByteBuf) msg;byte[] data = new byte[result.readableBytes()];result.readBytes(data);String resultStr = new String(data);// 接收並列印用戶端的資訊System.out.println("Client said:" + resultStr);// 釋放資源,這行很關鍵result.release();// 向用戶端發送訊息String response = "I am ok!";// 在當前情境下,發送的資料必須轉換成ByteBuf數組ByteBuf encoded = ctx.alloc().buffer(4 * response.length());encoded.writeBytes(response.getBytes());ctx.write(encoded);ctx.flush();
2、接收發送資料操作都是通過handler實現的,handler在netty中佔據了非常重要的位置。
class HelloServerInHandler extends ChannelInboundHandlerAdapter
3、netty的handler是基於事件觸發的,例如當client串連server成功後,client中的HelloClientIntHandler的channelActive方法會自動調用。
// 接收server端的訊息,並列印出來 @Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {System.out.println("client channelRead");ByteBuf result = (ByteBuf) msg; byte[] data=new byte[result.readableBytes()];result.readBytes(data);System.out.println("Server said:" + new String(data));result.release();}
4、ChannelInboundHandler之間的傳遞,通過調用 ctx.fireChannelRead(msg) 實現;調用ctx.write(msg) 將傳遞到ChannelOutboundHandler。
@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {log.debug("InboundHandler1 channelRead "+ctx);ctx.fireChannelRead(msg);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {log.debug("InboundHandler2 channelRead "+ctx);ByteBuf result=(ByteBuf)msg;byte[] data=new byte[result.readableBytes()];String res=new String(data);System.out.println("Client said: "+res);result.release();ctx.write(msg);}
5、ctx.write()方法執行後,需要調用flush()方法才能令它立即執行。
@Overridepublic void write(ChannelHandlerContext ctx, Object msg,ChannelPromise promise) throws Exception {log.debug("OutboundHandler1 write");String str="i am ok";ByteBuf encoded=ctx.alloc().buffer(str.length()*4);encoded.writeBytes(str.getBytes());ctx.write(encoded);ctx.flush();}
6、ChannelOutboundHandler 在註冊的時候需要放在最後一個ChannelInboundHandler之前,否則將無法傳遞到ChannelOutboundHandler。
ChannelPipeline pipeline=ch.pipeline(); pipeline.addLast(new OutboundHandler1());pipeline.addLast(new OutboundHandler2()); pipeline.addLast(new InboundHandler1());pipeline.addLast(new InboundHandler2());
7、Encoder、Decoder的本質也是Handler,它們的執行順序、使用方法與Handler保持一致。
執行順序是:Encoder 先註冊的後執行,與OutboundHandler一致;Decoder是先註冊的先執行,與InboundHandler一致。