GRPC--Node篇 相互通信

本文详细介绍了在Node.js环境中如何使用gRPC进行前后端通信。通过同一个.proto文件,分别编写server.js和client.js,实现helloWorld.proto及user.proto的通信。文中提到安装必要的依赖,如grpc-tools、google-protobuf和grpc,并通过编译命令生成服务端和客户端所需文件。通过启动服务端和客户端,完成'hello, world'的示例交互,强调了server.js和client.js中方法与.proto文件中定义的消息类型的对应关系。" 50441620,1182515,PHP获取当前及前几个月份的方法,"['PHP', '日期时间', '函数应用']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GRPC(Node)


前后端遵循同一个.proto文件来写各自的代码。
本文写的是node如何调通gRPC服务。

  • 传个文本
  • helloWorld.proto
  • 传个对象
  • user.proto

如何使用一个.proto文件

首先得安装依赖包:

  • npm install grpc-tools --save-dev
  • npm install google-protobuf --save
  • npm install grpc --save

再运行编译命令
./node_modules/grpc-tools/bin/protoc --js_out=import_style=commonjs,binary:./ --plugin=protoc-gen-grpc=./node_modules/grpc-tools/bin/grpc_node_plugin.exe --grpc_out=./ xxx.proto
这里注意 ./ 和 .proto文件之间有个空格

运行完成后,会生成xxx_grpc_pb.js 和 xxx_pb.js两个文件


helloWorld.proto

syntax = "proto3";

package helloWorld;

service HelloWorld{
  rpc hello (Request) returns (Response) {
  }
}

message Request{
  string msg = 1;
}

message Response{
  string msg = 1;
}

server.js 文件

const grpc = require("grpc");
const services = require("./helloWorld_grpc_pb.js");
const messages = require("./helloWorld_pb.js");
const hello = function(call, callback) {
   
   
  const response = new messages.Response();
  response.setMsg("hello, " + call.request.getMsg());
  callback(null, response);
};
const server = new grpc.Server(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值