1

gRPC 的新手,我正在尝试使用 grpc 流式传输视频文件,客户端和服务器都在 Node 中,运行服务时,我可以控制台记录服务器端的缓冲区,但是我无法从客户端获取任何内容, 谁能帮帮我,谢谢!

视频.proto:

syntax = "proto3";

package videoservice;

service VideoService {
  rpc callVideo (EmptyRequest) returns (stream VideoResponse);
}

message EmptyRequest {}

message VideoResponse {
  bytes videoStream = 1;
}

server.js 中的实现:

var PROTO_PATH = __dirname + '/video.proto';

var fs = require('fs');
var grpc = require('grpc');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {keepCase: true,
     longs: String,
     enums: String,
     defaults: true,
     oneofs: true
    });
var videoservice = grpc.loadPackageDefinition(packageDefinition).videoservice;

function callVideo(call) {
    let videoDataStream = fs.createReadStream('./sample.mp4');
    videoDataStream.on('data',function(chunk){
        console.log(chunk);
        call.write(chunk);
    }).on('end',function(){
        call.end();
    })
}

function getServer() {
  var server = new grpc.Server();
  server.addService(videoservice.VideoService.service, {
    callVideo: callVideo
  });
  return server;
}

if (require.main === module) {
  // If this is run as a script, start a server on an unused port
  var videoServer = getServer();
  videoServer.bind('0.0.0.0:9090', grpc.ServerCredentials.createInsecure());
  videoServer.start();
}

exports.getServer = getServer;

和client.js:

var PROTO_PATH = __dirname + '/video.proto';

var grpc = require('grpc');
var protoLoader = require('@grpc/proto-loader');
var packageDefinition = protoLoader.loadSync(
    PROTO_PATH,
    {keepCase: true,
     longs: String,
     enums: String,
     defaults: true,
     oneofs: true
    });
var vs = grpc.loadPackageDefinition(packageDefinition).videoservice;

const REMOTE_URL = "localhost:9090";
let client = new vs.VideoService(REMOTE_URL, grpc.credentials.createInsecure());

client.callVideo({}).on('data',function(chunk){
    console.log(chunk.videoStream);
});

下面是输出,左边是进入 gRPC 通道之前服务器端缓冲区的内容,右边是客户端的结果,每个块中没有任何内容: 在此处输入图像描述

4

1 回答 1

3

这将有助于解决您的问题:

function callVideo(call) {
    const videoDataStream = fs.createReadStream('./sample.mp4');

    videoDataStream.on('data', (chunk) => {
        console.log(chunk);
        call.write({ videoStream: chunk });
    });
    
    videoDataStream.on('end', () => {
        call.end();
    });
}

不要注意改变代码的样式。这里的主要内容是call.write({videoStream: chunk});

于 2020-06-20T09:16:00.003 回答