DotNetty - 当我在处理之前在管道中使用解码器时,我得到消息处理两次
问题描述:
我对DotNetty相当陌生,并且发现了以下问题。DotNetty - 当我在处理之前在管道中使用解码器时,我得到消息处理两次
我已经通过Netty的例子和文档。
从处理POCO(POJO; s)时看到的建议设计是创建Decorder类,该类实现解码方法并将IByteBuffer转换为合适的POCO。 然后,ServerHandler(InboundHandler)将使用POCO作为其消息。 这看起来非常整齐,我喜欢整洁。我所要做的就是创建解码器将其添加到管道中,并发生魔法。
差不多。 我现在面临的问题是,我这样做的时候,我得到了由ServerHandler(InboundHandler)处理两次的相同POCO。 对于此示例,我简化了代码,以便解码器将IbyteBuffer转换为字符串,并将ServerHandler输出至控制台。
见下文代码: -
public class ToTextDecoder : ByteToMessageDecoder
{
protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output)
{
var clientMessage = input.ToString(Encoding.UTF8);
output.Add(clientMessage);
}
}
public class RawConsoleWritingFromTextServerHandler : SimpleChannelInboundHandler<string> {
protected override void ChannelRead0(IChannelHandlerContext context, string message) {
Console.WriteLine("********************************************");
Console.WriteLine("Server received message from client : " + message);
Console.WriteLine("********************************************");
}
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception e) {
//Console.WriteLine("{0}", e.ToString());
ctx.CloseAsync();
}
}
和引导程序
var bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup)
.Channel<TcpServerSocketChannel>()
.Option(ChannelOption.SoBacklog, 100)
.Handler(new LoggingHandler("LSTN"))
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
var pipeline = channel.Pipeline;
if (tlsCertificate != null)
{
pipeline.AddLast(TlsHandler.Server(tlsCertificate));
}
pipeline.AddLast(new LoggingHandler("CONN"));
pipeline.AddLast(new ToTextDecoder());
pipeline.AddLast(new RawConsoleWritingFromTextServerHandler());
}));
IChannel bootstrapChannel = await bootstrap.BindAsync(ServerSettings.Port);
Console.WriteLine("---------------Server Ready-------------------------------");
Console.ReadLine();
答
的docoder需要清除输入缓冲器。使用buffer.clear或其他一些读取,将缓冲区按照已读取的方向移动。