@Bodden

Почему client gRPC не подключается к service gRPC?

Здравствуйте.
На METANIT.COM взял пример для изучения, все вроде скопировал правильно, но получаю ошибку.
Server:
internal class Program
{   
    private static void Main(string[] args)
    {
       
        var builder = WebApplication.CreateBuilder(args);

        // добавляем сервисы для работы с gRPC
        builder.Services.AddGrpc();

        var app = builder.Build();

        // настраиваем обработку HTTP-запросов
        app.MapGrpcService<GreeterService>();
        app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client...");

        app.Run();
    }
  
}

namespace ProtoBuild.Services
{
    public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;
        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}

662904564dc66382372802.jpeg
Ptoto
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

//option java_multiple_files = true;
//option java_package = "io.grpc.examples.helloworld";
//option java_outer_classname = "HelloWorldProto";
//option objc_class_prefix = "HLW";
option csharp_namespace = "ProtoBuild";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <None Remove="Protos\helloworld.proto" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.26.1" />
    <PackageReference Include="Grpc.AspNetCore.Server" Version="2.62.0" />
    <PackageReference Include="Grpc.Net.Client" Version="2.62.0" />
    <PackageReference Include="Grpc.Tools" Version="2.62.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
  </ItemGroup>

</Project>


Client:
using Grpc.Net.Client;
using ProtoBuildClient;

internal class Program
{
    private static async Task Main(string[] args)
    {
        // создаем канал для обмена сообщениями с сервером
        // параметр - адрес сервера gRPC
        using var channel = GrpcChannel.ForAddress("http://localhost:5000");
        // создаем клиент
        var client = new Greeter.GreeterClient(channel);
        Console.Write("Введите имя: ");
        string? name = Console.ReadLine();
        // обмениваемся сообщениями с сервером
        var reply = await client.SayHelloAsync(new HelloRequest { Name = name });
        Console.WriteLine($"Ответ сервера: {reply.Message}");
        Console.ReadKey();

        }
    }

// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

syntax = "proto3";

//option java_multiple_files = true;
//option java_package = "io.grpc.examples.helloworld";
//option java_outer_classname = "HelloWorldProto";
//option objc_class_prefix = "HLW";
option csharp_namespace = "ProtoBuildClient";

//package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

662904ceb8361892786963.jpeg

Server сидит на порту 5000
662905326ef21081461067.jpeg
66290539378e9004023846.jpeg
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Google.Protobuf" Version="3.26.1" />
    <PackageReference Include="Grpc.Net.Client" Version="2.62.0" />
    <PackageReference Include="Grpc.Tools" Version="2.62.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

	<ItemGroup>
		<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
	</ItemGroup>

</Project>


Ошибка:
Unhandled exception. Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: The HTTP/2 server closed the connection.

В Visual Studio тоже все собралось. Помогите пожалуйста, мозг уже кипит.
  • Вопрос задан
  • 73 просмотра
Пригласить эксперта
Ответы на вопрос 1
AshBlade
@AshBlade Куратор тега C#
Просто хочу быть счастливым
Скорее всего проблема с версией HTTP. На сервере открой порт для gRPC и пропиши в нем HTTP/2 использование.

appsettings.json

"Kestrel": {
    "Endpoints": {
      "gRPC": {
        "Url": "http://localhost:5000"
        "Protocols": "Http2"
      }
    }
  }
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы