Home > Back-end >  Handle network issues when wi-fi is switched off
Handle network issues when wi-fi is switched off

Time:04-04

I am testing .NET version of gRPC to understand how to handle network failures. I put the server to one external machine and debugging the client. The server ticks with a message onnce a second and the client just shows it on the console. So when I stop my local Wi-Fi connection for seconds, then gRPC engine automatically recovers and I even get remaining values. However, if I disable Wi-Fi for longer time like a minute, then it just gets stuck. I don't even get any exceptions so that I can just handle this case and recover manually. This scenario works fine when I close the server app manually, then an exception will occur on the client. This is what I have on the client:

static async Task Main(string[] args)
{
    try
    {
        await Subscribe();
    }
    catch (Exception)
    {
        Console.WriteLine("Fail");
        Thread.Sleep(1000);
        await Main(args);
    }

    Console.ReadLine();
}

private static async Task Subscribe()
{
    using var channel = GrpcChannel.ForAddress("http://x.x.x.x:5555");
    var client = new Greeter.GreeterClient(channel);
    var replies = client.GerReplies(new HelloRequest { Message = "Test" });
    while (await replies.ResponseStream.MoveNext(CancellationToken.None))
    {
        Console.WriteLine(replies.ResponseStream.Current.Message);
    }
    Console.WriteLine("Completed");
}

This works when the server app stopped but it doesn't work if I just disable loca Wi-Fi connection on the client side. How can I handle such a case and similar ones?

CodePudding user response:

I've managed to solve it by KeepAlivePingDelay setting:

var handler = new SocketsHttpHandler
{
    KeepAlivePingDelay = TimeSpan.FromSeconds(5),
    KeepAlivePingTimeout = TimeSpan.FromSeconds(5),
};
using var channel = GrpcChannel.ForAddress("http://x.x.x.x:5555", new GrpcChannelOptions
{
    HttpHandler = handler
});

This configuration force gRPC fail after 10 seconds in case of no connection.

  • Related