简体   繁体   中英

GRPC client streaming in node.js

I'm trying to implement client streaming in GRPC using node.js as the client (the server is in .NET).

This the proto file:

syntax = "proto3";

package groom;

import "google/protobuf/timestamp.proto";

message NewsFlash  {
    google.protobuf.Timestamp news_time=1;
    string news_item=2;
}

message NewsStreamStatus  {
    bool success=1;
}

service Groom  {
    rpc SendNewsFlash(stream NewsFlash) returns (NewsStreamStatus);
}

And this is the code I use:

const grpc = require("@grpc/grpc-js");
var protoLoader = require("@grpc/proto-loader");
const PROTO_PATH = "./Protos/groom.proto";
const options = {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true,
};

const newsItems=["Item1","Item2","Item3","Item4","Item5"]

var grpcObj = protoLoader.loadSync(PROTO_PATH, options);
const GroomService = grpc.loadPackageDefinition(grpcObj).groom.Groom;

const clientStub = new GroomService(
   "localhost:5054",
   grpc.credentials.createInsecure()
);

var call = clientStub.sendNewsFlash(function(error, newsStatus) {
  if (error) {
    console.error(error);
  }
  console.log('Stream success: ', newsStatus.success);
});

for (var i=0;i<5;i++)  {
  var itemIndex=Math.floor(Math.random() * 5);
  call.write({news_item: newsItems[itemIndex]});
}

call.end();

The code runs just fine, but the problem is that it's not really streaming the data. It looks like all the messages are sent to the server when the call.end() method is called, and just then the server gets the messages, and not when the client calls the call.write(...) method.

When using BloomRPC to simulate the call, it works just fine and the server gets the message as soon as it is sent.

Why doesn't the code stream the messages? Why do they sent only after the call.end() method is called?

Your call.write and call.end lines are all synchronous within the same function, which means that they don't leave time for any other asynchronous work to happen in between. The gRPC library does some asynchronous work when sending messages, and all of that happens after you call end and let other asynchronous work happen.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM