1

我正在使用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));

}

}

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

非常感谢!

4

2 回答 2

1

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

于 2013-05-23T09:56:49.513 回答
0

多谢你们!所以我添加了以下内容:

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 在那里/客户端代码相同),但现在我必须执行上述步骤才能使其工作...... ……?

于 2013-05-24T02:00:24.813 回答