簡體   English   中英

node.js 中的 GRPC 客戶端流式傳輸

[英]GRPC client streaming in node.js

我正在嘗試使用 node.js 作為客戶端(服務器在 .NET 中)在 GRPC 中實現客戶端流式傳輸。

這是原始文件:

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);
}

這是我使用的代碼:

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();

代碼運行得很好,但問題是它並沒有真正流式傳輸數據。 看起來當call.end()方法時所有消息都發送到服務器,然后服務器獲取消息,而不是在客戶端調用call.write(...)方法時。

使用 BloomRPC 模擬調用時,它工作得很好,服務器一發送就得到消息。

為什么代碼 stream 沒有消息? 為什么它們僅在call.end()方法后才發送?

您的call.writecall.end行在同一個 function 中都是同步的,這意味着它們不會為任何其他異步工作留出時間在其間發生。 gRPC 庫在發送消息時會做一些異步工作,所有這些都發生在您調用end並讓其他異步工作發生之后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM