是否可以通过gRCP Web(http / 1.1)进行cleint服务器流式响应?
我有一个可以正常工作的客户端/服务器+数据库解决方案,但似乎我必须等待服务器的完整响应(请参阅服务器中的//await Task.Delay(2000);
)
我想发生的是,客户端应该在发送回客户端的每个“服务器标记”上进行渲染,而不是等待流关闭并呈现完整的响应。
有任何想法吗?
协议
syntax = "proto3";
option csharp_namespace = "GrpcReports";
package reports;
service Reports {
rpc AllReports (ReportRequest) returns (stream ReportReply);
}
message ReportRequest {}
message ReportReply {
string name = 1;
}
服务器
// server
public class ReportsService : Reports.ReportsBase
{
private readonly IReportRepository _repository;
private readonly IMapper _mapper;
public ReportsService(IReportRepository repository, IMapper mapper)
{
_repository = repository ?? throw new ArgumentNullException(nameof(IReportRepository));
_mapper = mapper ?? throw new ArgumentNullException(nameof(IMapper));
}
public override async Task AllReports(ReportRequest request, IServerStreamWriter<ReportReply> responseStream, ServerCallContext context)
{
foreach (var item in _mapper.Map<List<ReportReply>>(await _repository.GetAllReportsAsync()))
{
Log.Information("{@ReportReply}", item);
await responseStream.WriteAsync(item);
//await Task.Delay(2000);
}
}
}
客户
@page "/"
@using Grpc.Core
@using GrpcReports
@using AutoMapper
@inject Reports.ReportsClient _reportsClient
@inject IMapper _mapper
<h1>Invoke gRPC service</h1>
<button @onclick="AllReports" class="btn btn-primary">Call gRPC service</button>
<p>Server report response from database:</p>
<ul>
@foreach (var item in reportReplys)
{
<li>@item.Name</li>
}
</ul>
@code {
List<ReportReply> reportReplys = new List<ReportReply>();
async Task AllReports()
{
using (var call = _reportsClient.AllReports(new ReportRequest()))
{
while (await call.ResponseStream.MoveNext())
{
reportReplys.Add(call?.ResponseStream?.Current);
}
}
}
}
答案 0 :(得分:0)
因此gRPC Web流确实可以正常工作,我唯一需要添加的就是在每个服务器刻度上重新呈现UI。
您唯一需要添加到代码中的是StateHasChanged();
。
客户端侧更新:
while (await call?.ResponseStream?.MoveNext())
{
reportReplys.Add(call?.ResponseStream?.Current);
StateHasChanged();
}