目录
创建protobuf message
syntax = "proto3";
option go_package= "./;pb";
package pb;
service Greeter {
// 服务端 推送流
rpc GetStream (StreamReqData) returns (stream StreamResData){}
}
// request
message StreamReqData {
string data = 1;
}
// response
message StreamResData {
string data = 1;
}
编译
protoc --go_out=./pb ./pb/hello.proto
protoc --go-grpc_out=./pb ./pb/hello.proto
生成的文件
hello.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.19.3
// source: pb/hello.proto
package pb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
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)
)
// request
type StreamReqData struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}
func (x *StreamReqData) Reset() {
*x = StreamReqData{}
if protoimpl.UnsafeEnabled {
mi := &file_pb_hello_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StreamReqData) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StreamReqData) ProtoMessage() {}
func (x *StreamReqData) ProtoReflect() protoreflect.Message {
mi := &file_pb_hello_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StreamReqData.ProtoReflect.Descriptor instead.
func (*StreamReqData) Descriptor() ([]byte, []int) {
return file_pb_hello_proto_rawDescGZIP(), []int{0}
}
func (x *StreamReqData) GetData() string {
if x != nil {
return x.Data
}
return ""
}
// response
type StreamResData struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}
func (x *StreamResData) Reset() {
*x = StreamResData{}
if protoimpl.UnsafeEnabled {
mi := &file_pb_hello_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *StreamResData) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*StreamResData) ProtoMessage() {}
func (x *StreamResData) ProtoReflect() protoreflect.Message {
mi := &file_pb_hello_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use StreamResData.ProtoReflect.Descriptor instead.
func (*StreamResData) Descriptor() ([]byte, []int) {
return file_pb_hello_proto_rawDescGZIP(), []int{1}
}
func (x *StreamResData) GetData() string {
if x != nil {
return x.Data
}
return ""
}
var File_pb_hello_proto protoreflect.FileDescriptor
var file_pb_hello_proto_rawDesc = []byte{
0x0a, 0x0e, 0x70, 0x62, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x12, 0x02, 0x70, 0x62, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65,
0x71, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20,
0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72,
0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x40,
0x0a, 0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x35, 0x0a, 0x09, 0x47, 0x65, 0x74,
0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53, 0x74, 0x72, 0x65,
0x61, 0x6d, 0x52, 0x65, 0x71, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53,
0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x22, 0x00, 0x30, 0x01,
0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2f, 0x3b, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
0x33,
}
var (
file_pb_hello_proto_rawDescOnce sync.Once
file_pb_hello_proto_rawDescData = file_pb_hello_proto_rawDesc
)
func file_pb_hello_proto_rawDescGZIP() []byte {
file_pb_hello_proto_rawDescOnce.Do(func() {
file_pb_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_hello_proto_rawDescData)
})
return file_pb_hello_proto_rawDescData
}
var file_pb_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pb_hello_proto_goTypes = []interface{}{
(*StreamReqData)(nil), // 0: pb.StreamReqData
(*StreamResData)(nil), // 1: pb.StreamResData
}
var file_pb_hello_proto_depIdxs = []int32{
0, // 0: pb.Greeter.GetStream:input_type -> pb.StreamReqData
1, // 1: pb.Greeter.GetStream:output_type -> pb.StreamResData
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_pb_hello_proto_init() }
func file_pb_hello_proto_init() {
if File_pb_hello_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_pb_hello_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StreamReqData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_pb_hello_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*StreamResData); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_pb_hello_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_pb_hello_proto_goTypes,
DependencyIndexes: file_pb_hello_proto_depIdxs,
MessageInfos: file_pb_hello_proto_msgTypes,
}.Build()
File_pb_hello_proto = out.File
file_pb_hello_proto_rawDesc = nil
file_pb_hello_proto_goTypes = nil
file_pb_hello_proto_depIdxs = nil
}
hello_grpc.pb.go
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
package pb
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.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// GreeterClient is the client API for Greeter 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 GreeterClient interface {
// 服务端 推送流
GetStream(ctx context.Context, in *StreamReqData, opts ...grpc.CallOption) (Greeter_GetStreamClient, error)
}
type greeterClient struct {
cc grpc.ClientConnInterface
}
func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
return &greeterClient{cc}
}
func (c *greeterClient) GetStream(ctx context.Context, in *StreamReqData, opts ...grpc.CallOption) (Greeter_GetStreamClient, error) {
stream, err := c.cc.NewStream(ctx, &Greeter_ServiceDesc.Streams[0], "/pb.Greeter/GetStream", opts...)
if err != nil {
return nil, err
}
x := &greeterGetStreamClient{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
}
type Greeter_GetStreamClient interface {
Recv() (*StreamResData, error)
grpc.ClientStream
}
type greeterGetStreamClient struct {
grpc.ClientStream
}
func (x *greeterGetStreamClient) Recv() (*StreamResData, error) {
m := new(StreamResData)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
// 服务端 推送流
GetStream(*StreamReqData, Greeter_GetStreamServer) error
mustEmbedUnimplementedGreeterServer()
}
// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}
func (UnimplementedGreeterServer) GetStream(*StreamReqData, Greeter_GetStreamServer) error {
return status.Errorf(codes.Unimplemented, "method GetStream not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}
// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
mustEmbedUnimplementedGreeterServer()
}
func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
s.RegisterService(&Greeter_ServiceDesc, srv)
}
func _Greeter_GetStream_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(StreamReqData)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(GreeterServer).GetStream(m, &greeterGetStreamServer{stream})
}
type Greeter_GetStreamServer interface {
Send(*StreamResData) error
grpc.ServerStream
}
type greeterGetStreamServer struct {
grpc.ServerStream
}
func (x *greeterGetStreamServer) Send(m *StreamResData) error {
return x.ServerStream.SendMsg(m)
}
// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
ServiceName: "pb.Greeter",
HandlerType: (*GreeterServer)(nil),
Methods: []grpc.MethodDesc{},
Streams: []grpc.StreamDesc{
{
StreamName: "GetStream",
Handler: _Greeter_GetStream_Handler,
ServerStreams: true,
},
},
Metadata: "pb/hello.proto",
}
服务器端
package main
import (
"fmt"
"net"
pb "pro01/pb"
"time"
"google.golang.org/grpc"
)
const PORT = ":50051"
type server struct {
pb.UnimplementedGreeterServer
}
//服务端 单向流
func (s *server) GetStream(req *pb.StreamReqData, res pb.Greeter_GetStreamServer) error {
i := 0
for {
i++
res.Send(&pb.StreamResData{Data: fmt.Sprintf("%v", time.Now().Unix())})
time.Sleep(1 * time.Second)
if i > 10 {
break
}
}
return nil
}
func main() {
//监听端口
lis, err := net.Listen("tcp", PORT)
if err != nil {
return
}
//创建一个grpc 服务器
s := grpc.NewServer()
//注册事件
pb.RegisterGreeterServer(s, &server{})
//处理链接
s.Serve(lis)
}
客户端实现
package main
import (
"context"
"log"
pb "pro01/pb"
"google.golang.org/grpc"
_ "google.golang.org/grpc/balancer/grpclb"
)
const (
ADDRESS = "localhost:50051"
)
func main() {
//通过grpc 库 建立一个连接
conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
if err != nil {
return
}
defer conn.Close()
//通过刚刚的连接 生成一个client对象。
c := pb.NewGreeterClient(conn)
//调用服务端推送流
reqstreamData := &pb.StreamReqData{Data: "aaa"}
res, _ := c.GetStream(context.Background(), reqstreamData)
for {
aa, err := res.Recv()
if err != nil {
log.Println(err)
break
}
log.Println(aa)
}
}
运行
go run server/main.go
go run client/main.go
运行结果
客户端输出
2022/09/17 15:57:05 data:"1646279825"
2022/09/17 15:57:06 data:"1646279826"
2022/09/17 15:57:07 data:"1646279827"
2022/09/17 15:57:08 data:"1646279828"
2022/09/17 15:57:09 data:"1646279829"
2022/09/17 15:57:10 data:"1646279830"
2022/09/17 15:57:11 data:"1646279831"
2022/09/17 15:57:12 data:"1646279832"
2022/09/17 15:57:13 data:"1646279833"
2022/09/17 15:57:14 data:"1646279834"
2022/09/17 15:57:15 data:"1646279835"
2022/09/17 15:57:16 EOF