1. 程式人生 > >【初學與研發之NETTY】netty4之物件、位元組傳輸

【初學與研發之NETTY】netty4之物件、位元組傳輸

netty4中的物件、位元組傳輸做了封裝,writeAndFlush中提供的引數Object可以直接的寫入物件、byte[]。不管是位元組陣列還是物件,關鍵部分的程式碼如下:

new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    
		    p.addLast("encoder", new ObjectEncoder());
                    p.addLast("decoder", new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)));
                   
                    p.addLast("handler", new UploadServerHandler());
                }
             }


其中,new ObjectDecoder(Integer.MAX_VALUE, ClassResolvers.cacheDisabled(null)),Integer.MAX_VALUE是設定傳輸的物件大小。預設為1M,設定如:

new ObjectDecoder(ClassResolvers.cacheDisabled(null))

xxxHandler類繼承ChannelInboundHandlerAdapter。

channel.writeAndFlush(new Object());

channel.writeAndFlush(new byte[10]);