dotNetty 代理 - 等待响应后再继续

dotNetty proxy - wait for response before continuing

提问人:f.lechleitner 提问时间:10/2/2023 更新时间:10/2/2023 访问量:16

问:

我已经使用 dotNetty 编写了一个 TCP 代理,到目前为止它运行良好!但是现在我在等待代理连接到的服务器的响应时遇到了问题。

服务器接受客户端连接,在主处理程序的 ChannelActive 方法中,我正在创建连接到另一台服务器的第二个通道。然后,我可以将消息从客户端发送到第二台服务器,还可以监听从第二台服务器到客户端的消息并转换这些消息。客户端有一条消息,需要来自服务器的一些信息才能正确翻译该消息。

因此,在主处理程序的 ChannelRead 方法中,我正在检查消息类型并发送所需的消息类型以收集所需的信息。我只是将该信息存储为通道属性。但是,如何保证在发送下一条消息之前已经处理了来自服务器的响应呢?

我已经标记了我希望 outboundChannel 在继续以下代码片段中的下一条消息之前等待响应的位置:

internal class SapChannelInboundHandler : SimpleChannelInboundHandler<ISapTelegram>
{

    private IChannel outboundChannel;

    public override async void ChannelActive(IChannelHandlerContext context)
    {
        Console.WriteLine("SapChannelInboundHandler - Channel active");

        context.Channel.GetAttribute(SfsServer.SapTelegramsToAcknowledge).Set(new List<ISapTelegram>());

        var inboundChannel = context.Channel;

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.Group(inboundChannel.EventLoop);

        if (ServerSettings.UseLibuv)
        {
            bootstrap.Channel<TcpChannel>();
        }
        else
        {
            bootstrap.Channel<TcpSocketChannel>();
        }

        bootstrap.Option(ChannelOption.AutoRead, true); // <-- important!
        bootstrap.Handler(new MesChannelInitializer(inboundChannel));

        outboundChannel = await bootstrap.ConnectAsync("127.0.0.1",8015);
        

    }


    protected async override void ChannelRead0(IChannelHandlerContext ctx, ISapTelegram msg)
    {

        List<ISapTelegram> openTelegrams = ctx.Channel.GetAttribute(SfsServer.SapTelegramsToAcknowledge).Get();
        if (msg.Header.Handshake != "AK")
        {
            openTelegrams.Add(msg);
        }


        if(msg.Header.TelegramType == SapTelegramType.DS)
        {
            var symbolicPointInformationRequest = new MesGetProductionAreaInformationTelegram();
            symbolicPointInformationRequest.InfoType = 3;

            await outboundChannel.WriteAndFlushAsync(symbolicPointInformationRequest);

            // <--------------------- I need to make sure that a response has beenreceived and processed before continuing here

        }
        

        if (outboundChannel.Active)
        {
            await outboundChannel.WriteAndFlushAsync(msg);
        }

    }

    public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

    public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
    {
        Console.WriteLine("SapChannelInboundHandler - Exception: " + exception);
        context.CloseAsync();
    }
}

有什么方法可以等待回复吗?或者,如果已收到响应,我是否可以设置布尔值 ChannelAttribute,然后使线程休眠(可能 10 毫秒),直到设置属性?谢谢!

C# .NET 异步 netty dotnetty

评论


答: 暂无答案