gRPC-一元呼叫C#
我试图通过制作一个简单的项目服务器/客户机来学习gRPC,客户机发送2个Int变量,服务器将用一个字符串和客户机发送的2个变量进行响应 协议缓冲区代码为:gRPC-一元呼叫C#,c#,gps,protocol-buffers,C#,Gps,Protocol Buffers,我试图通过制作一个简单的项目服务器/客户机来学习gRPC,客户机发送2个Int变量,服务器将用一个字符串和客户机发送的2个变量进行响应 协议缓冲区代码为: syntax = "proto3"; option csharp_namespace = "MapPB"; service MapRoute { rpc Gps(Location) returns (LocationName) {} } message Location { int32 la = 1; in
syntax = "proto3";
option csharp_namespace = "MapPB";
service MapRoute {
rpc Gps(Location) returns (LocationName) {}
}
message Location {
int32 la = 1;
int32 lo = 2;
}
message LocationName {
string Name = 1;
}
服务器
using Grpc.Core;
using static MapPB.MapRoute;
using MapPB;
namespace gServer
{
public class gS : MapRouteBase
{
public override async Task<LocationName> Gps(Location request, ServerCallContext context)
{
return await base.Gps(new LocationName { Name = "Your Location is " + request.La + ":" + request.Lo } );
}
}
class Program
{
const int Port = 50051;
static void Main(string[] args)
{
Server server = new Server
{
Services = { MapRoute.BindService(new gS()) },
Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
};
server.Start();
Console.WriteLine("Map server listening on port " + Port);
Console.WriteLine("Press any key to stop the server...");
Console.ReadKey();
server.ShutdownAsync().Wait();
}
}
}
我在.Gps
没有给定与“MapRoute.MapRouteBase.Gps(位置,ServerCallContext)”的必需形式参数“context”对应的参数
我试图向参数添加上下文
,但出现了另一个错误
无法从“MapPB.LocationName”转换为“MapPB.Location”
有人能解释一下我做错了什么吗 您的服务功能实现应该如下所示:
public override async Task<LocationName> Gps(Location request, ServerCallContext context)
{
return new LocationName { Name = "Your Location is " + request.La + ":" + request.Lo };
}
公共覆盖异步任务Gps(位置请求,ServerCallContext上下文)
{
return new LocationName{Name=“您的位置是”+request.La+”:“+request.Lo};
}
其思想是,每当客户机调用该函数时,就会自动调用该函数。它向您传递定义的参数(此处的位置)。您需要返回结果,即此处的位置名称
您在这里犯的错误是将处理委托给基类,而不是自己处理请求。作为对Matthias247答案的更新,我更愿意这样看(即使他的答案也是正确的):
尝试
returnnewlocationname{Name=“您的位置是”+request.La+”:“+request.Lo}代码>我猜基类是抽象的,你不应该委托给它。是的,谢谢你,很好-我把它转换成了一个答案
public override async Task<LocationName> Gps(Location request, ServerCallContext context)
{
return new LocationName { Name = "Your Location is " + request.La + ":" + request.Lo };
}
public override Task<LocationName> Gps(Location request, ServerCallContext context)
{
return Task.FromResult(new LocationName
{
Name = "Your Location is " + request.La + ":" + request.Lo
});
}
static async Task Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:50021", ChannelCredentials.Insecure);
var client = new MapRouteClient(channel);
int la = 1;
int lo = 2;
var reply = await client.GpsAsync(new MapPB.Location { La = la , Lo = lo });
Console.WriteLine(reply.Name);
channel.ShutdownAsync().Wait();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}