MessageToMessageDecoder

MessageToMessageDecoder

我尝试执行简单的Web套接字解码,然后进行编码,但是当它通过TextWebsocketDecoder处理程序时,我遇到了此异常:

io.netty.channel.DefaultChannelPipeline$TailContext exceptionCaught
WARNING: An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.util.IllegalReferenceCountException: refCnt: 0, decrement: 1
    at io.netty.buffer.AbstractReferenceCountedByteBuf.release(AbstractReferenceCountedByteBuf.java:101)
    at io.netty.buffer.DefaultByteBufHolder.release(DefaultByteBufHolder.java:73)
    at io.netty.util.ReferenceCountUtil.release(ReferenceCountUtil.java:59)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:112)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:103)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
    at io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler$1.channelRead(WebSocketServerProtocolHandler.java:147)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
    at io.netty.channel.ChannelInboundHandlerAdapter.channelRead(ChannelInboundHandlerAdapter.java:86)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:276)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:263)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:318)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:304)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:137)
    at java.lang.Thread.run(Thread.java:745)

我所拥有的是简单的Initializer,可以在TextWebsocketEncoder之前找到它:
public class ServerInitializer extends ChannelInitializer<Channel> {
    private final ChannelGroup group;

    public GameServerInitializer(ChannelGroup group) {
        this.group = group;
    }

    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpRequestHandler("/ws"));
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        pipeline.addLast(new TextWebSocketFrameHandler(group));
        pipeline.addLast("textWebsocketDecoder",new TextWebsocketDecoder());
        pipeline.addLast("textWebsocketEncoder",new TextWebsocketEncoder());
    }
}

TextWebSocketFrameHandler
public class TextWebSocketFrameHandler  extends SimpleChannelInboundHandler<TextWebSocketFrame>{
     private final ChannelGroup group;

        public TextWebSocketFrameHandler(ChannelGroup group) {
            this.group = group;
        }

        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
            if (evt == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {

                ctx.pipeline().remove(HttpRequestHandler.class);

                group.writeAndFlush(new TextWebSocketFrame("Client " + ctx.channel() + " joined"));

                group.add(ctx.channel());

            } else {
                super.userEventTriggered(ctx, evt);
            }
        }

        @Override
        public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
             ctx.fireChannelRead(msg);
            //group.writeAndFlush(msg.retain());
        }
}

这是TextWebsocketDecoder和TextWebsocketEncoder:

TextWebsocketDecoder:
public class TextWebsocketDecoder extends MessageToMessageDecoder<TextWebSocketFrame>
{

    @Override
    protected void decode(ChannelHandlerContext ctx, TextWebSocketFrame frame, List<Object> out) throws Exception
    {
        String json = frame.text();
        JSONObject jsonObject = new JSONObject(json);
        int type = jsonObject.getInt("type");
        JSONArray msgJsonArray = jsonObject.getJSONArray("msg");
        String user = msgJsonArray.getString(0);
        String pass = msgJsonArray.getString(1);
        String connectionkey = msgJsonArray.getString(2);
        int timestamp = jsonObject.getInt("timestamp");

        JSONObject responseJson = new JSONObject();
        responseJson.put("type",Config.LOGIN_SUCCESS);
        responseJson.put("connectionkey",connectionkey);

        out.add(responseJson); // After This im getting the exception !!!
    }
}

TextWebsocketEncoder
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class TextWebsocketEncoder extends MessageToMessageEncoder<JSONObject>
{

    @Override
    protected void encode(ChannelHandlerContext arg0, JSONObject arg1, List<Object> out) throws Exception {
        String json = arg1.toString();
        out.add(new TextWebSocketFrame(json));
    }

}

最佳答案

异常(exception)

在TextWebSocketFrameHandler内部,您正在调用ctx.fireChannelRead(msg);,这会将消息向上传递1条链,但是MessageToMessageDecoder不准备处理此问题。为了解释这个问题,我需要解释MessageToMessageDecoder的工作方式。
MessageToMessageDecoder的工作原理是捕获上游的每条消息并将它们传递给您的自定义代码,您的自定义代码处理工作,而mtmd处理关闭您传入的资源。

由于将引用传递给另一端,因此实际上多次关闭了WebSocketFrame,从而导致错误。 MessageToMessageDecoder甚至在javadoc中警告您。

要解决该问题,请按照手册中的说明进行操作,并让我们的 channel 阅读以下内容:

@Override
public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
     msg.retain(); // ferrybig: fixed bug http://stackoverflow.com/q/34634750/1542723
     ctx.fireChannelRead(msg);
     //group.writeAndFlush(msg.retain());
}

不退回的问题

在您的注释中,您声明该代码不会发回任何东西。这是预料之中的,因为您的管道仅消耗数据并将其传递到整个链中。要解决此问题,您需要在管道上进行一些返工。
  • 我们需要交换json-webframe解码器和编码器的顺序:
    pipeline.addLast("textWebsocketDecoder",new TextWebsocketEncoder());
    pipeline.addLast("textWebsocketEncoder",new TextWebsocketDecoder());
    

    这是因为您的解码器正在生成将被发送回处理程序链的输出,如果解码器高于该输出,则编码器将不会看到此输出。 (不应将您的解码器称为以netty命名的解码器)
  • 我们需要更改您的解码器,以将生成的数据实际发送回↑链而不是↓到不存在的void中。

    为了进行这些更改,我们将让TextWebSocketDecoder扩展ChannelInboundHandlerAdapter而不是MessageToMessageDecoder<TextWebSocketFrame>,因为我们正在处理消息,而不是将消息传递给其他处理程序。

    我们将解码方法的签名更改为channelRead(ChannelHandlerContext ctx, Object msg),并添加一些样板代码:
    public void channelRead(ChannelHandlerContext ctx, Object msg) /* throws Exception */
        TextWebSocketFrame frame = (TextWebSocketFrame) msg;
        try {
            /* Remaining code, follow the steps further of see end result */
        } finally {
            frame.release();
        }
    }
    
  • 我们调整代码以使结果向上传递而不是向下传递:
    public void channelRead(ChannelHandlerContext ctx, Object msg) /* throws Exception */
        TextWebSocketFrame frame = (TextWebSocketFrame) msg;
        try {
    
            String json = frame.text();
            JSONObject jsonObject = new JSONObject(json);
            int type = jsonObject.getInt("type");
            JSONArray msgJsonArray = jsonObject.getJSONArray("msg");
            String user = msgJsonArray.getString(0);
            String pass = msgJsonArray.getString(1);
            String connectionkey = msgJsonArray.getString(2);
            int timestamp = jsonObject.getInt("timestamp");
    
            JSONObject responseJson = new JSONObject();
            responseJson.put("type",Config.LOGIN_SUCCESS);
            responseJson.put("connectionkey",connectionkey);
    
            ctx.writeAndFlush(responseJson)
        } finally {
            frame.release();
        }
    }
    

  • 请注意,您可能很想从异常中删除我们之前的代码,但是这样做会在netty的异步特性下运行时触发未定义的行为。

    10-02 21:38