简述区别
请求类型 | 方法名 | 描述 | 示例场景 |
---|---|---|---|
一元请求 | UnaryEcho | 客户端发送单个请求,服务端返回单个响应。 | 简单查询或操作 |
服务端流 | ServerStreamingEcho | 客户端发送单个请求,服务端返回一个流的响应。 | 分页、持续更新 |
客户端流 | ClientStreamingEcho | 客户端发送一个流的请求,服务端返回单个响应。 | 文件上传 |
双向流 | BidirectionalStreamingEcho | 客户端和服务端之间可以同时发送和接收流数据。 | 聊天系统 |
.proto
syntax = "proto3";
// go导入路径,仅仅与go的命名空间相关,与package无关
option go_package = "golang12-g-rpc/echo"; // 指定生成的 Go 代码的包路径为 golang12-g-rpc/echo。这是为了让生成的代码符合 Go 的模块结构。
// 指定代码生成路径
// 表示生成的 Go 文件会放在 golang12-g-rpc/echo 目录中。
// 例子
// option go_package = "github.com/wymli/bc_sns/dep/pb/go/enumx;enumx";
// 这里逗号(;)
// 后面是就是生成go代码时,package名
// 前面是生成代码时,如果其他proto 引用 了这个proto,那么他们就会使用逗号(;)前面的作为go包路径// .proto导入路径
import "google/protobuf/timestamp.proto"; // 导入 Google 提供的 Timestamp 类型,用于表示时间戳。 这里是要在.proto文件使用timestamp中定义的内容// .proto命名空间
package grpc.echo; // 定义 Protocol Buffers协议缓冲区 的包名。生成的 Go 代码会包含该包名,通常在 Go 的 proto 文件中对应 import grpc.echo。
// 定义了一个 grpc.echo 命名空间,
// 主要用于在另一个.proto文件引用本文件定义的东西,例如 grpc.echo.EchoRequest = {...}
// 如果在另一个 .proto 文件中有相同的消息或服务名,但不同的包名,这些定义不会冲突。
// 生成的 Go 代码中会使用这个 package 作为标识。
// import "grpc.echo"message EchoRequest {string message = 1; // 分配字段编号必须唯一bytes bytes = 2; // 数字 19,000 到 19,999 保留给 Protocol Buffers 实现。如果您在消息中使用这些保留的字段编号之一,协议缓冲区编译器将发出警告。int32 length = 3; // 字段使用后不能更改,“更改”字段编号等同于删除该字段并使用相同类型但新编号创建一个新字段google.protobuf.Timestamp time = 4; // 字段编号 永远不应重复使用// 您应该将字段编号 1 到 15 用于最常设置的字段。较低的字段编号值在线格式中占用更少的空间。例如,范围 1 到 15 内的字段编号需要一个字节来编码。
}message EchoResponse {string message = 1;bytes bytes = 2;int32 length = 3;google.protobuf.Timestamp time = 4;
}service Echo {// 一元请求// 客户端发送单个请求,服务端返回单个响应。rpc UnaryEcho(EchoRequest) returns(EchoResponse) {}// 服务端流// 客户端发送单个请求,服务端返回一个流的响应。// 如分页或持续更新rpc ServerStreamingEcho(EchoRequest) returns(stream EchoResponse) {}// 客户端流// 客户端发送一个流的请求,服务端返回单个响应。// 如文件上传rpc ClientStreamingEcho(stream EchoRequest) returns(EchoResponse) {}// 双向流// 客户端和服务端之间可以同时发送和接收流数据。// 如聊天系统rpc BidirectionalStreamingEcho(stream EchoRequest) returns(stream EchoResponse) {}
}
- 生成消息代码
protoc --go_out=. --go_opt=paths=source_relative .\echo\echo.proto
code
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.35.2
// protoc v5.29.1
// source: echo/echo.protopackage echo // 由 go_package 的最后一级路径控制import (protoreflect "google.golang.org/protobuf/reflect/protoreflect"protoimpl "google.golang.org/protobuf/runtime/protoimpl"timestamppb "google.golang.org/protobuf/types/known/timestamppb"reflect "reflect"sync "sync"
)const (// Verify that this generated code is sufficiently up-to-date._ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)// Verify that runtime/protoimpl is sufficiently up-to-date._ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)type EchoRequest struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCacheunknownFields protoimpl.UnknownFieldsMessage string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`Bytes []byte `protobuf:"bytes,2,opt,name=bytes,proto3" json:"bytes,omitempty"`Length int32 `protobuf:"varint,3,opt,name=length,proto3" json:"length,omitempty"`Time *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=time,proto3" json:"time,omitempty"`
}func (x *EchoRequest) Reset() {*x = EchoRequest{}mi := &file_echo_echo_proto_msgTypes[0]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)
}func (x *EchoRequest) String() string {return protoimpl.X.MessageStringOf(x)
}func (*EchoRequest) ProtoMessage() {}func (x *EchoRequest) ProtoReflect() protoreflect.Message {mi := &file_echo_echo_proto_msgTypes[0]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {ms.StoreMessageInfo(mi)}return ms}return mi.MessageOf(x)
}// Deprecated: Use EchoRequest.ProtoReflect.Descriptor instead.
func (*EchoRequest) Descriptor() ([]byte, []int) {return file_echo_echo_proto_rawDescGZIP(), []int{0}
}func (x *EchoRequest) GetMessage() string {if x != nil {return x.Message}return ""
}func (x *EchoRequest) GetBytes() []byte {if x != nil {return x.Bytes}return nil
}func (x *EchoRequest) GetLength() int32 {if x != nil {return x.Length}return 0
}func (x *EchoRequest) GetTime() *timestamppb.Timestamp {if x != nil {return x.Time}return nil
}type EchoResponse struct {state protoimpl.MessageStatesizeCache protoimpl.SizeCacheunknownFields protoimpl.UnknownFieldsMessage string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`Bytes []byte `protobuf:"bytes,2,opt,name=bytes,proto3" json:"bytes,omitempty"`Length int32 `protobuf:"varint,3,opt,name=length,proto3" json:"length,omitempty"`Time *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=time,proto3" json:"time,omitempty"`
}func (x *EchoResponse) Reset() {*x = EchoResponse{}mi := &file_echo_echo_proto_msgTypes[1]ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))ms.StoreMessageInfo(mi)
}func (x *EchoResponse) String() string {return protoimpl.X.MessageStringOf(x)
}func (*EchoResponse) ProtoMessage() {}func (x *EchoResponse) ProtoReflect() protoreflect.Message {mi := &file_echo_echo_proto_msgTypes[1]if x != nil {ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))if ms.LoadMessageInfo() == nil {ms.StoreMessageInfo(mi)}return ms}return mi.MessageOf(x)
}// Deprecated: Use EchoResponse.ProtoReflect.Descriptor instead.
func (*EchoResponse) Descriptor() ([]byte, []int) {return file_echo_echo_proto_rawDescGZIP(), []int{1}
}func (x *EchoResponse) GetMessage() string {if x != nil {return x.Message}return ""
}func (x *EchoResponse) GetBytes() []byte {if x != nil {return x.Bytes}return nil
}func (x *EchoResponse) GetLength() int32 {if x != nil {return x.Length}return 0
}func (x *EchoResponse) GetTime() *timestamppb.Timestamp {if x != nil {return x.Time}return nil
}var File_echo_echo_proto protoreflect.FileDescriptorvar file_echo_echo_proto_rawDesc = []byte{0x0a, 0x0f, 0x65, 0x63, 0x68, 0x6f, 0x2f, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74,0x6f, 0x12, 0x09, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x1a, 0x1f, 0x67, 0x6f,0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69,0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x85, 0x01,0x0a, 0x0b, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a,0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07,0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73,0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x16, 0x0a,0x06, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x6c,0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x2e, 0x0a, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20,0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f,0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52,0x04, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x86, 0x01, 0x0a, 0x0c, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65,0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67,0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52,0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68,0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x06, 0x6c, 0x65, 0x6e, 0x67, 0x74, 0x68, 0x12, 0x2e,0x0a, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67,0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54,0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x04, 0x74, 0x69, 0x6d, 0x65, 0x32, 0xb3,0x02, 0x0a, 0x04, 0x45, 0x63, 0x68, 0x6f, 0x12, 0x3e, 0x0a, 0x09, 0x55, 0x6e, 0x61, 0x72, 0x79,0x45, 0x63, 0x68, 0x6f, 0x12, 0x16, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f,0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x67,0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x73,0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x12, 0x4a, 0x0a, 0x13, 0x53, 0x65, 0x72, 0x76, 0x65,0x72, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x45, 0x63, 0x68, 0x6f, 0x12, 0x16,0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52,0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63,0x68, 0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,0x00, 0x30, 0x01, 0x12, 0x4a, 0x0a, 0x13, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x53, 0x74, 0x72,0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x45, 0x63, 0x68, 0x6f, 0x12, 0x16, 0x2e, 0x67, 0x72, 0x70,0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65,0x73, 0x74, 0x1a, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x45,0x63, 0x68, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00, 0x28, 0x01, 0x12,0x53, 0x0a, 0x1a, 0x42, 0x69, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x61, 0x6c,0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x69, 0x6e, 0x67, 0x45, 0x63, 0x68, 0x6f, 0x12, 0x16, 0x2e,0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68, 0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65,0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x2e, 0x65, 0x63, 0x68,0x6f, 0x2e, 0x45, 0x63, 0x68, 0x6f, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x00,0x28, 0x01, 0x30, 0x01, 0x42, 0x15, 0x5a, 0x13, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x31, 0x32,0x2d, 0x67, 0x2d, 0x72, 0x70, 0x63, 0x2f, 0x65, 0x63, 0x68, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f,0x74, 0x6f, 0x33,
}var (file_echo_echo_proto_rawDescOnce sync.Oncefile_echo_echo_proto_rawDescData = file_echo_echo_proto_rawDesc
)func file_echo_echo_proto_rawDescGZIP() []byte {file_echo_echo_proto_rawDescOnce.Do(func() {file_echo_echo_proto_rawDescData = protoimpl.X.CompressGZIP(file_echo_echo_proto_rawDescData)})return file_echo_echo_proto_rawDescData
}var file_echo_echo_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_echo_echo_proto_goTypes = []any{(*EchoRequest)(nil), // 0: grpc.echo.EchoRequest(*EchoResponse)(nil), // 1: grpc.echo.EchoResponse(*timestamppb.Timestamp)(nil), // 2: google.protobuf.Timestamp
}
var file_echo_echo_proto_depIdxs = []int32{2, // 0: grpc.echo.EchoRequest.time:type_name -> google.protobuf.Timestamp2, // 1: grpc.echo.EchoResponse.time:type_name -> google.protobuf.Timestamp0, // 2: grpc.echo.Echo.UnaryEcho:input_type -> grpc.echo.EchoRequest0, // 3: grpc.echo.Echo.ServerStreamingEcho:input_type -> grpc.echo.EchoRequest0, // 4: grpc.echo.Echo.ClientStreamingEcho:input_type -> grpc.echo.EchoRequest0, // 5: grpc.echo.Echo.BidirectionalStreamingEcho:input_type -> grpc.echo.EchoRequest1, // 6: grpc.echo.Echo.UnaryEcho:output_type -> grpc.echo.EchoResponse1, // 7: grpc.echo.Echo.ServerStreamingEcho:output_type -> grpc.echo.EchoResponse1, // 8: grpc.echo.Echo.ClientStreamingEcho:output_type -> grpc.echo.EchoResponse1, // 9: grpc.echo.Echo.BidirectionalStreamingEcho:output_type -> grpc.echo.EchoResponse6, // [6:10] is the sub-list for method output_type2, // [2:6] is the sub-list for method input_type2, // [2:2] is the sub-list for extension type_name2, // [2:2] is the sub-list for extension extendee0, // [0:2] is the sub-list for field type_name
}func init() { file_echo_echo_proto_init() }
func file_echo_echo_proto_init() {if File_echo_echo_proto != nil {return}type x struct{}out := protoimpl.TypeBuilder{File: protoimpl.DescBuilder{GoPackagePath: reflect.TypeOf(x{}).PkgPath(),RawDescriptor: file_echo_echo_proto_rawDesc,NumEnums: 0,NumMessages: 2,NumExtensions: 0,NumServices: 1,},GoTypes: file_echo_echo_proto_goTypes,DependencyIndexes: file_echo_echo_proto_depIdxs,MessageInfos: file_echo_echo_proto_msgTypes,}.Build()File_echo_echo_proto = out.Filefile_echo_echo_proto_rawDesc = nilfile_echo_echo_proto_goTypes = nilfile_echo_echo_proto_depIdxs = nil
}
- 生成 gRPC 服务代码
protoc --go-grpc_out=. --gogrpc_opt=paths=source_relative .\echo\echo.proto
code
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v5.29.1
// source: echo/echo.protopackage echo // 由 go_package 的最后一级路径控制import (context "context"grpc "google.golang.org/grpc"codes "google.golang.org/grpc/codes"status "google.golang.org/grpc/status"
)// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9const (Echo_UnaryEcho_FullMethodName = "/grpc.echo.Echo/UnaryEcho"Echo_ServerStreamingEcho_FullMethodName = "/grpc.echo.Echo/ServerStreamingEcho"Echo_ClientStreamingEcho_FullMethodName = "/grpc.echo.Echo/ClientStreamingEcho"Echo_BidirectionalStreamingEcho_FullMethodName = "/grpc.echo.Echo/BidirectionalStreamingEcho"
)// EchoClient is the client API for Echo service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type EchoClient interface {// 一元请求UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error)// 服务端流ServerStreamingEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[EchoResponse], error)// 客户端流ClientStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[EchoRequest, EchoResponse], error)// 双向流BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[EchoRequest, EchoResponse], error)
}type echoClient struct {cc grpc.ClientConnInterface
}func NewEchoClient(cc grpc.ClientConnInterface) EchoClient {return &echoClient{cc}
}func (c *echoClient) UnaryEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (*EchoResponse, error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)out := new(EchoResponse)err := c.cc.Invoke(ctx, Echo_UnaryEcho_FullMethodName, in, out, cOpts...)if err != nil {return nil, err}return out, nil
}func (c *echoClient) ServerStreamingEcho(ctx context.Context, in *EchoRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[EchoResponse], error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)stream, err := c.cc.NewStream(ctx, &Echo_ServiceDesc.Streams[0], Echo_ServerStreamingEcho_FullMethodName, cOpts...)if err != nil {return nil, err}x := &grpc.GenericClientStream[EchoRequest, EchoResponse]{ClientStream: stream}if err := x.ClientStream.SendMsg(in); err != nil {return nil, err}if err := x.ClientStream.CloseSend(); err != nil {return nil, err}return x, nil
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_ServerStreamingEchoClient = grpc.ServerStreamingClient[EchoResponse]func (c *echoClient) ClientStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (grpc.ClientStreamingClient[EchoRequest, EchoResponse], error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)stream, err := c.cc.NewStream(ctx, &Echo_ServiceDesc.Streams[1], Echo_ClientStreamingEcho_FullMethodName, cOpts...)if err != nil {return nil, err}x := &grpc.GenericClientStream[EchoRequest, EchoResponse]{ClientStream: stream}return x, nil
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_ClientStreamingEchoClient = grpc.ClientStreamingClient[EchoRequest, EchoResponse]func (c *echoClient) BidirectionalStreamingEcho(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[EchoRequest, EchoResponse], error) {cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)stream, err := c.cc.NewStream(ctx, &Echo_ServiceDesc.Streams[2], Echo_BidirectionalStreamingEcho_FullMethodName, cOpts...)if err != nil {return nil, err}x := &grpc.GenericClientStream[EchoRequest, EchoResponse]{ClientStream: stream}return x, nil
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_BidirectionalStreamingEchoClient = grpc.BidiStreamingClient[EchoRequest, EchoResponse]// EchoServer is the server API for Echo service.
// All implementations must embed UnimplementedEchoServer
// for forward compatibility.
type EchoServer interface {// 一元请求UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error)// 服务端流ServerStreamingEcho(*EchoRequest, grpc.ServerStreamingServer[EchoResponse]) error// 客户端流ClientStreamingEcho(grpc.ClientStreamingServer[EchoRequest, EchoResponse]) error// 双向流BidirectionalStreamingEcho(grpc.BidiStreamingServer[EchoRequest, EchoResponse]) errormustEmbedUnimplementedEchoServer()
}// UnimplementedEchoServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedEchoServer struct{}func (UnimplementedEchoServer) UnaryEcho(context.Context, *EchoRequest) (*EchoResponse, error) {return nil, status.Errorf(codes.Unimplemented, "method UnaryEcho not implemented")
}
func (UnimplementedEchoServer) ServerStreamingEcho(*EchoRequest, grpc.ServerStreamingServer[EchoResponse]) error {return status.Errorf(codes.Unimplemented, "method ServerStreamingEcho not implemented")
}
func (UnimplementedEchoServer) ClientStreamingEcho(grpc.ClientStreamingServer[EchoRequest, EchoResponse]) error {return status.Errorf(codes.Unimplemented, "method ClientStreamingEcho not implemented")
}
func (UnimplementedEchoServer) BidirectionalStreamingEcho(grpc.BidiStreamingServer[EchoRequest, EchoResponse]) error {return status.Errorf(codes.Unimplemented, "method BidirectionalStreamingEcho not implemented")
}
func (UnimplementedEchoServer) mustEmbedUnimplementedEchoServer() {}
func (UnimplementedEchoServer) testEmbeddedByValue() {}// UnsafeEchoServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to EchoServer will
// result in compilation errors.
type UnsafeEchoServer interface {mustEmbedUnimplementedEchoServer()
}func RegisterEchoServer(s grpc.ServiceRegistrar, srv EchoServer) {// If the following call pancis, it indicates UnimplementedEchoServer was// embedded by pointer and is nil. This will cause panics if an// unimplemented method is ever invoked, so we test this at initialization// time to prevent it from happening at runtime later due to I/O.if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {t.testEmbeddedByValue()}s.RegisterService(&Echo_ServiceDesc, srv)
}func _Echo_UnaryEcho_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {in := new(EchoRequest)if err := dec(in); err != nil {return nil, err}if interceptor == nil {return srv.(EchoServer).UnaryEcho(ctx, in)}info := &grpc.UnaryServerInfo{Server: srv,FullMethod: Echo_UnaryEcho_FullMethodName,}handler := func(ctx context.Context, req interface{}) (interface{}, error) {return srv.(EchoServer).UnaryEcho(ctx, req.(*EchoRequest))}return interceptor(ctx, in, info, handler)
}func _Echo_ServerStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {m := new(EchoRequest)if err := stream.RecvMsg(m); err != nil {return err}return srv.(EchoServer).ServerStreamingEcho(m, &grpc.GenericServerStream[EchoRequest, EchoResponse]{ServerStream: stream})
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_ServerStreamingEchoServer = grpc.ServerStreamingServer[EchoResponse]func _Echo_ClientStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {return srv.(EchoServer).ClientStreamingEcho(&grpc.GenericServerStream[EchoRequest, EchoResponse]{ServerStream: stream})
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_ClientStreamingEchoServer = grpc.ClientStreamingServer[EchoRequest, EchoResponse]func _Echo_BidirectionalStreamingEcho_Handler(srv interface{}, stream grpc.ServerStream) error {return srv.(EchoServer).BidirectionalStreamingEcho(&grpc.GenericServerStream[EchoRequest, EchoResponse]{ServerStream: stream})
}// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
type Echo_BidirectionalStreamingEchoServer = grpc.BidiStreamingServer[EchoRequest, EchoResponse]// Echo_ServiceDesc is the grpc.ServiceDesc for Echo service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Echo_ServiceDesc = grpc.ServiceDesc{ServiceName: "grpc.echo.Echo",HandlerType: (*EchoServer)(nil),Methods: []grpc.MethodDesc{{MethodName: "UnaryEcho",Handler: _Echo_UnaryEcho_Handler,},},Streams: []grpc.StreamDesc{{StreamName: "ServerStreamingEcho",Handler: _Echo_ServerStreamingEcho_Handler,ServerStreams: true,},{StreamName: "ClientStreamingEcho",Handler: _Echo_ClientStreamingEcho_Handler,ClientStreams: true,},{StreamName: "BidirectionalStreamingEcho",Handler: _Echo_BidirectionalStreamingEcho_Handler,ServerStreams: true,ClientStreams: true,},},Metadata: "echo/echo.proto",
}
SendAndClose、Send、CloseAndRecv 和 CloseSend 的适用场景总结
- SendAndClose 和 CloseAndRecv:配对使用于 客户端流模式。
- 主要用在结尾判断是否需要结束流时通知对方
服务器用 SendAndClose 发送总结性响应。 服务端收完后要send结束信号,然后close自身流
客户端用 CloseAndRecv 接收总结性响应。 因为是客户端一直发,所以发完要close,并且recv服务端的接收完毕信号
- Send 和 CloseSend:配对使用于 服务器流或双向流模式。send在客户端流模式也可以用,只要是发送。
服务器用 Send 不断发送消息。
客户端用 CloseSend 表示完成发送,同时继续接收服务器响应。
client
package clientimport ("context""fmt""golang12-g-rpc/echo""google.golang.org/protobuf/types/known/timestamppb""io""log""os""strconv""sync""time"
)func CallUnary(client echo.EchoClient) {ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()in := &echo.EchoRequest{Message: "client send message",Time: timestamppb.New(time.Now()),}res, err := client.UnaryEcho(ctx, in)if err != nil {log.Fatal(err)}fmt.Printf("client recv: %v\n", res.Message)}func CallServerStream(client echo.EchoClient) {ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()in := &echo.EchoRequest{Message: "client send message",Time: timestamppb.New(time.Now()),}stream, err := client.ServerStreamingEcho(ctx, in)if err != nil {log.Fatal(err)}filename := "echoClient/files/" + strconv.FormatInt(time.Now().UnixMilli(), 10) + ".jpg"// os.O_APPEND 写的时候附加内容,即在原来基础上写file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) // perm含义 文件 所有者可读写,同用户组可读,其他用户可读if err != nil {log.Fatal(err)}defer file.Close()for {res, err := stream.Recv()if err == io.EOF {break}if err != nil {log.Println(err)break}file.Write(res.Bytes[:res.Length])fmt.Printf("client recv: %v\n", res.Message)}stream.CloseSend() // 适用场景:双向流或服务器流模式。// 作用:告诉服务器客户端的数据发送完成,但不阻塞等待服务器响应。
}func CallClientStream(client echo.EchoClient) {filePath := "echoClient/files/client.jpg"file, err := os.Open(filePath)if err != nil {log.Fatal(err)}defer file.Close()ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()stream, err := client.ClientStreamingEcho(ctx)if err != nil {log.Fatal(err)}buf := make([]byte, 1024)for {n, err := file.Read(buf)if err == io.EOF {break}if err != nil {log.Fatal(err)}stream.Send(&echo.EchoRequest{Message: "client sending file",Bytes: buf[:n],Time: timestamppb.New(time.Now()),Length: int32(n),})}res, err := stream.CloseAndRecv() // 适用场景:客户端流模式。// 作用:关闭客户端的流(即发送完成)。同时阻塞等待服务器返回一个最终响应。// 当客户端发送完数据后,需要告诉服务器 "我发完了",并等待服务器处理所有收到的数据后返回一个最终响应。if err != nil {log.Fatal(err)}fmt.Printf("client recv: %v\n", res.Message)
}func CallBidirectional(client echo.EchoClient) {ctx, cancel := context.WithTimeout(context.Background(), time.Second)defer cancel()stream, err := client.BidirectionalStreamingEcho(ctx)if err != nil {log.Fatal(err)}wg := &sync.WaitGroup{}wg.Add(1)go func() {defer wg.Done()// 客户端发送filePath := "echoClient/files/client.jpg"file, err := os.Open(filePath)if err != nil {log.Fatal(err)}defer file.Close()buf := make([]byte, 1024)for {n, err := file.Read(buf)if err == io.EOF {break}if err != nil {log.Fatal(err)}stream.Send(&echo.EchoRequest{Message: "client sending file",Bytes: buf[:n],Time: timestamppb.New(time.Now()),Length: int32(n),})}stream.CloseSend()}()wg.Add(1)go func() {defer wg.Done()filename := "echoClient/files/" + strconv.FormatInt(time.Now().UnixMilli(), 10) + ".jpg"// os.O_APPEND 写的时候附加内容,即在原来基础上写file, err := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) // perm含义 文件 所有者可读写,同用户组可读,其他用户可读if err != nil {log.Fatal(err)}defer file.Close() for { res, err := stream.Recv() if err == io.EOF { break }if err != nil { log.Println(err) break }file.Write(res.Bytes[:res.Length]) fmt.Printf("client recv: %v\n", res.Message) }stream.CloseSend() }()wg.Wait()
}
main
package mainimport ("flag""golang12-g-rpc/echo""golang12-g-rpc/echoClient/client""google.golang.org/grpc""google.golang.org/grpc/credentials/insecure""log"
)var (addr = flag.String("addr", "localhost:50051", "")
)func main() {flag.Parse()conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(insecure.NewCredentials()))if err != nil {log.Fatal(err)}defer conn.Close()c := echo.NewEchoClient(conn)//client.CallUnary(c)//client.CallServerStream(c)//client.CallClientStream(c)client.CallBidirectional(c)
}
server
package serverimport ("context""fmt""golang12-g-rpc/echo""google.golang.org/protobuf/types/known/timestamppb""io""log""os""strconv""sync""time"
)type EchoServer struct {echo.UnimplementedEchoServer
}func (EchoServer) UnaryEcho(ctx context.Context, in *echo.EchoRequest) (*echo.EchoResponse, error) {fmt.Printf("server recv : %v\n", in.Message)return &echo.EchoResponse{Message: "server send message",}, nil
}
func (EchoServer) ServerStreamingEcho(in *echo.EchoRequest, stream echo.Echo_ServerStreamingEchoServer) error {fmt.Printf("server recv : %v\n", in.Message)filePath := "echoServer/files/server.jpg"file, err := os.Open(filePath)if err != nil {log.Fatal(err)}defer file.Close()buf := make([]byte, 1024)for {n, err := file.Read(buf)if err == io.EOF {break}if err != nil {return err}stream.Send(&echo.EchoResponse{Message: "server sending file",Bytes: buf[:n],Time: timestamppb.New(time.Now()),Length: int32(n),})}// 服务端return nil / error 即表示流结束return nil
}
func (EchoServer) ClientStreamingEcho(stream echo.Echo_ClientStreamingEchoServer) error {filePath := "echoServer/files/" + strconv.FormatInt(time.Now().UnixMilli(), 10) + ".jpg"file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)if err != nil {log.Fatal(err)}defer file.Close()for {req, err := stream.Recv()if err == io.EOF {break}if err != nil {log.Println(err)return err}file.Write(req.Bytes[:req.Length])fmt.Printf("server recv: %v\n", req.Message)}// 如果服务器端不调用 SendAndClose:客户端的 CloseAndRecv 会因为没有接收到最终响应而阻塞,导致程序卡住或超时。err = stream.SendAndClose(&echo.EchoResponse{Message: "server send message",})return nil
}
func (EchoServer) BidirectionalStreamingEcho(stream echo.Echo_BidirectionalStreamingEchoServer) error {wg := &sync.WaitGroup{}wg.Add(1)go func() {defer wg.Done()// 接收客户端流,保存文件filePath := "echoServer/files/" + strconv.FormatInt(time.Now().UnixMilli(), 10) + ".jpg"file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)if err != nil {log.Fatal(err)}defer file.Close()for {req, err := stream.Recv()if err == io.EOF {break}if err != nil {log.Println(err)return}file.Write(req.Bytes[:req.Length])fmt.Printf("server recv: %v\n", req.Message)}}()wg.Add(1)go func() {defer wg.Done()// 发送到客户端流,发送文件filePath := "echoServer/files/server.jpg"file, err := os.Open(filePath)if err != nil {log.Fatal(err)}defer file.Close()buf := make([]byte, 1024)for { n, err := file.Read(buf) if err == io.EOF { break }if err != nil { return }stream.Send(&echo.EchoResponse{ Message: "server sending file", Bytes: buf[:n], Time: timestamppb.New(time.Now()), Length: int32(n), })}}()wg.Wait() return nil
}
main
package mainimport ("flag""fmt""golang12-g-rpc/echo""golang12-g-rpc/echoServer/server""google.golang.org/grpc""log""net"
)var (// 定义命令行参数port = flag.Int("port", 50051, "")
)func main() {flag.Parse()lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))if err != nil {log.Fatal(err)}s := grpc.NewServer()echo.RegisterEchoServer(s, &server.EchoServer{})log.Printf("server listening at : %v\n", lis.Addr())if err := s.Serve(lis); err != nil {log.Fatal(err)}
}