首页 > 解决方案 > 如何配置 GRPC 双向流以在 .NET 中发送字节

问题描述

我正在尝试通过我的双向流发送几千字节的消息。我正在测试流来回发送数据的速度,但是当我尝试写入时,我似乎无法获得要显示的实际值。理想情况下,我希望流尽可能快地来回发送 KB,但现在我无法让它显示。当我尝试运行时,我得到了 Google.Protobuf.ByteString。

这是原型:

service Racer {
  rpc ReadySetGo (stream RaceMessageRequest) returns (stream RaceMessageReply);
}

message RaceMessageRequest {
  int32 countRequest = 1;
  bytes byteRequest = 2;
}

message RaceMessageReply{
    int32 countReply = 1;
    bytes byteReply = 2;
}

和服务:

public override async Task ReadySetGo(
  IAsyncStreamReader<RaceMessageRequest> requestStream, 
  IServerStreamWriter<RaceMessageReply> responseStream,
  ServerCallContext context)
{
  ////////////////////////////////////
  //Creating a stream
  await foreach (var request in requestStream.ReadAllAsync())
  {
    var helloReply = new RaceMessageReply { CountReply = 25 + request.CountRequest };

    await responseStream.WriteAsync(helloReply);
  }

  //testing the binary data streaming
  await foreach (var request in requestStream.ReadAllAsync())
  {
    var hellobytes = new RaceMessageReply { ByteReply = ByteString.CopyFrom((byte)request.CountRequest) };

    await responseStream.WriteAsync(hellobytes);
  }
  ///////////////////////////////

我在主要方法中的代码:

byte[] bytes = BitConverter.GetBytes(10000);

      using var call = client.ReadySetGo();
      while (true)
      {
        // Send and receive messages over the stream
        await call.RequestStream.WriteAsync(new RaceMessageRequest { CountRequest = 24 });
        await call.RequestStream.WriteAsync(new RaceMessageRequest { ByteRequest = ByteString.CopyFrom(bytes) });
        await call.ResponseStream.MoveNext();

        //Console.WriteLine($"Greetings testing the basic format: {call.ResponseStream.Current.CountReply}");
        Console.WriteLine($"Greetings testing Byte stream: {call.ResponseStream.Current.ByteReply.ToString()}");

        Console.ReadKey();
      }

标签: c#.netprotocol-buffersgrpc

解决方案


推荐阅读