首页 > 解决方案 > Xamarin.Forms gRPC 启动 gRPC 调用时出错:连接上的流意外结束

问题描述

我为我的学习编写了一个应用程序。

我尝试在 Xamarin.Forms 中使用 gRPC。

gRPC 位于单独的 Libyry (.NET Standart 2.1) 中。如果我使用 WPF-Core Project 中的代码,一切正常。

但是,如果我尝试在我的 Xamarin.Forms-Project 中使用相同的连接,则连接不起作用。

如果我使用连接字符串“ http://my.server.com:5050 ”,我会得到这些异常

Error starting gRPC call: unexpected end of stream on Connection{my.server.com:5050, proxy=DIRECT hostAddress=5.189.149.82 cipherSuite=none protocol=http/1.1} (recycle count=0)

如果我使用 SSL 版本“ https://my.server.com:5050 ”,我会收到这些异常

Error starting gRPC call: Connection closed by peer

这是 gRPC-Libary 的代码

...
        if (connectionString.Contains("http://"))
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

        channel = GrpcChannel.ForAddress(connectionString);
        client = new Haushaltsbuch.HaushaltsbuchClient(channel);

        SuccsessReply reply = new SuccsessReply { Result = false };

        try
        {
            reply = client.Login(new UserRequest
            {
                User = new GRPC_User
                {
                    Username = username,
                    PassHash = passHash
                }
            });
        }
        catch (RpcException e) when (e.Status.Detail.Contains("The SSL connection could not be established"))
        {
            client = null;
            throw new CommunicationException("Fehler mit SSL-Zertifikat des Servers", e);
        }
        catch (RpcException e)
        {
            client = null;
            throw new CommunicationException("Server nicht erreichbar", e);
        }
...

我只是一名学生,如果我用谷歌搜索,就会发现 Xamarin Forms 支持 gRPC。但为什么它不起作用?

.Android 项目安装了来自 NuGet 的 GRPC.Core 包。

标签: c#androidxamarin.formsgrpc

解决方案


通过更换解决了

channel = GrpcChannel.ForAddress(connectionString);

        if (connectionString.Contains("http://"))
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            string newConString = connectionString.Replace("http://", "");
            return new Channel(newConString, ChannelCredentials.Insecure);
        }
        else
        {
            string newConString = connectionString.Replace("https://", "");
            return new Channel(newConString, new SslCredentials());
        }

似乎 GrpcChannel 类不适用于 Andriod。


推荐阅读