0
我對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();