å¨ä¸é¢ä»£ç ä¸
public class EchoServerHandler extends SimpleChannelInboundHandler {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
System.out.println(
"server receive: " + in.toString(CharsetUtil.UTF_8)
//æ¤å¤åæ¥å¼å¸¸io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
ctx.write(in);
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
super.channelReadComplete(ctx);
ctx.flush();
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
å¨channelRead0()æ¹æ³ä¸çctx.write(in),ä¼æ¥io.netty.util.IllegalReferenceCountException
åå æ¯è¿æ¯å 为Nettyæå¼ç¨è®¡æ°å¨çåå ï¼èªä»Netty 4å¼å§ï¼å¯¹è±¡ççå½å¨æç±å®ä»¬çå¼ç¨è®¡æ°ï¼reference countsï¼ç®¡çï¼èä¸æ¯ç±åå¾æ¶éå¨ï¼garbage collectorï¼ç®¡çäºã
ByteBufæ¯æå¼å¾æ³¨æçï¼å®ä½¿ç¨äºå¼ç¨è®¡æ°æ¥æ¹è¿åé
å
ååéæ¾å
åçæ§è½ãå¨æ们å建ByteBuf对象åï¼å®çå¼ç¨è®¡æ°æ¯1ï¼å½ä½ éæ¾ï¼releaseï¼å¼ç¨è®¡æ°å¯¹è±¡æ¶ï¼å®çå¼ç¨è®¡æ°å1ï¼å¦æå¼ç¨è®¡æ°ä¸º0ï¼è¿ä¸ªå¼ç¨è®¡æ°å¯¹è±¡ä¼è¢«éæ¾ï¼deallocateï¼,并è¿åå¯¹è±¡æ± ã
å½å°è¯è®¿é®å¼ç¨è®¡æ°ä¸º0çå¼ç¨è®¡æ°å¯¹è±¡ä¼æåºIllegalReferenceCountExceptionå¼å¸¸ï¼
* Should be called by every method that tries to access the buffers content to check
* if the buffer was released before.
protected final void ensureAccessible() {
if (checkAccessible && refCnt() == 0) {
throw new IllegalReferenceCountException(0);
åºç¨æ°å»ºçBytebufè¿åæ°æ®ï¼
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
System.out.println(
"server receive: " + in.toString(CharsetUtil.UTF_8)
String str = in.toString(CharsetUtil.UTF_8);
* ctx.write(in);
* Bytebuf并ä¸éåç´æ¥éç¨ï¼å¿
é¡»æ°å»ºæè½åå客æ·ç«¯ï¼
* å¦åå°ä¼æ¥io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
* åå æ¯è¿æ¯å 为Netty4æå¼ç¨è®¡æ°å¨çåå ï¼èªä»Netty 4å¼å§ï¼å¯¹è±¡ççå½å¨æç±å®ä»¬çå¼ç¨è®¡æ°ï¼reference countsï¼ç®¡çï¼
* èä¸æ¯ç±åå¾æ¶éå¨ï¼garbage collectorï¼ç®¡çäºãByteBufæ¯æå¼å¾æ³¨æçï¼å®ä½¿ç¨äºå¼ç¨è®¡æ°æ¥æ¹è¿åé
å
ååéæ¾å
åçæ§è½ã
* å¨æ们å建ByteBuf对象åï¼å®çå¼ç¨è®¡æ°æ¯1ï¼å½ä½ éæ¾ï¼releaseï¼å¼ç¨è®¡æ°å¯¹è±¡æ¶ï¼å®çå¼ç¨è®¡æ°å1ï¼
* å¦æå¼ç¨è®¡æ°ä¸º0ï¼è¿ä¸ªå¼ç¨è®¡æ°å¯¹è±¡ä¼è¢«éæ¾ï¼deallocateï¼,并è¿åå¯¹è±¡æ± ã
* å½å°è¯è®¿é®å¼ç¨è®¡æ°ä¸º0çå¼ç¨è®¡æ°å¯¹è±¡ä¼æåºIllegalReferenceCountExceptionå¼å¸¸ï¼
* æè
å¨è¯¥Bytebuf å¨å¤ç¨åéè¦è°ç¨retain(),å°è®¡æ°å¨ç½®ä¸º1
ByteBuf pong = Unpooled.copiedBuffer(str.getBytes());
ctx.write(pong);
æè
å¨å¤ç¨åè°ç¨retain()æ¹æ³
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf in = (ByteBuf) msg;
System.out.println(
"server receive: " + in.toString(CharsetUtil.UTF_8)