【问题标题】:Netty 4.0 - StringDecoder and ChannelInboundMessageHandlerAdapter<String> not workingNetty 4.0 - StringDecoder 和 ChannelInboundMessageHandlerAdapter<String> 不工作
【发布时间】:2013-05-23 03:26:47
【问题描述】:

我正在使用 netty 4.0.0-CR3,遵循服务器端的示例: https://github.com/netty/netty/blob/master/example/src/main/java/io/netty/example/telnet/TelnetServerPipelineFactory.java

我的管道如下构建:

private static final StringDecoder DECODER = new StringDecoder(CharsetUtil.UTF_8);

@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("decoder", DECODER);
    // and then business logic
    pipeline.addLast("serverHandler", new ServerHandler());
}

和处理程序:

public class ServerHandler extends ChannelInboundMessageHandlerAdapter<String> {

private static final Logger LOGGER = LoggerFactory.getLogger(ServerHandler.class);

public void messageReceived(ChannelHandlerContext ctx, String request)
        throws Exception {
    // Displays the message
    LOGGER.info("Received: " + request);
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
        throws Exception {
    LOGGER.error("Unexpected exception from downstream.", cause);
    ctx.close();
}

}

我创建了一个简单的 C# 客户端,它将字符串编码为字节,然后发送到服务器。但是,我没有看到调用 StringDecoder 的 decode() 或处理程序的 messageReceived()。

然后我在管道中删除了 StringDecoder(),并将处理程序更改为:

public class Handler extends ChannelInboundByteHandlerAdapter {

@Override
protected void inboundBufferUpdated(ChannelHandlerContext ctx, ByteBuf in)
        throws Exception {
    System.out.println("called " + in.toString(CharsetUtil.UTF_8));

}

}

现在它可以正常工作了。从功能上讲,两个管道都应该正常工作吗?为什么第一个设置不起作用?客户端代码是一样的。

非常感谢!

【问题讨论】:

    标签: java netty


    【解决方案1】:

    StringDecoder 的文档明确指出,如果通过流连接(例如 TCP)使用,它必须与 ByteToMessageDecoder 结合使用。您引用的示例在 StringDecoder 前面有这样一个处理程序。

    【讨论】:

    • 正确。如果您正在处理基于行的协议,请在StringDecoder 之前添加LineBasedFrameDecoder
    【解决方案2】:

    谢谢各位!所以我添加了以下内容:

    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.nulDelimiter()));
    

    直到我在 C# 中明确地将 '\0' 添加到 String 的末尾,这仍然不起作用:

    ASCIIEncoding encoder = new ASCIIEncoding();
    int index = random.Next(0, 2);
    byte[] buffer = encoder.GetBytes(list[index] + "\0");
    

    奇怪的是,我之前使用的是 Netty 3.6,即使没有 FrameDecoder 也一切正常(只有 StringDecoder 在那里/客户端代码相同),但现在我必须执行上述步骤才能使其正常工作。 .........?

    【讨论】:

      猜你喜欢
      • 2015-11-15
      • 2014-08-12
      • 1970-01-01
      • 2014-09-27
      • 2013-02-21
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多