gRPC双向数据流快速体验

简介

双向数据流模式(Bidirectional streaming RPC) 顾名思义,这是客户端和服务端都可以向对方发送数据流,这个时候双方的数据可以同时互相发送,也就是可以实现实时交互。典型的应用场景是聊天机器人。

代码

由于这次实现的是双向数据流,需要保证接收数据和发送数据要保证并行,所以需要使用到协程。

proto

syntax = "proto3";
option go_package = ".;proto";

service AllStream{
  rpc AllStream(stream StreamRequestData) returns (stream StreamResponseData);
}

message StreamRequestData{
  string data = 1;
}

message StreamResponseData{
  string data = 1;
}

.pb.go

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.28.0
// 	protoc        v3.19.4
// source: allstream.proto

package proto

import (
	context "context"
	grpc "google.golang.org/grpc"
	codes "google.golang.org/grpc/codes"
	status "google.golang.org/grpc/status"
	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)
)

type StreamRequestData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamRequestData) Reset() {
	*x = StreamRequestData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_allstream_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamRequestData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamRequestData) ProtoMessage() {}

func (x *StreamRequestData) ProtoReflect() protoreflect.Message {
	mi := &file_allstream_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 StreamRequestData.ProtoReflect.Descriptor instead.
func (*StreamRequestData) Descriptor() ([]byte, []int) {
	return file_allstream_proto_rawDescGZIP(), []int{0}
}

func (x *StreamRequestData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

type StreamResponseData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamResponseData) Reset() {
	*x = StreamResponseData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_allstream_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamResponseData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamResponseData) ProtoMessage() {}

func (x *StreamResponseData) ProtoReflect() protoreflect.Message {
	mi := &file_allstream_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 StreamResponseData.ProtoReflect.Descriptor instead.
func (*StreamResponseData) Descriptor() ([]byte, []int) {
	return file_allstream_proto_rawDescGZIP(), []int{1}
}

func (x *StreamResponseData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

var File_allstream_proto protoreflect.FileDescriptor

var file_allstream_proto_rawDesc = []byte{
	0x0a, 0x0f, 0x61, 0x6c, 0x6c, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74,
	0x6f, 0x22, 0x27, 0x0a, 0x11, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65,
	0x73, 0x74, 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, 0x28, 0x0a, 0x12, 0x53, 0x74,
	0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 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, 0x45, 0x0a, 0x09, 0x41, 0x6c, 0x6c, 0x53, 0x74, 0x72, 0x65, 0x61,
	0x6d, 0x12, 0x38, 0x0a, 0x09, 0x41, 0x6c, 0x6c, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x12,
	0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x44, 0x61,
	0x74, 0x61, 0x1a, 0x13, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
	0x6e, 0x73, 0x65, 0x44, 0x61, 0x74, 0x61, 0x28, 0x01, 0x30, 0x01, 0x42, 0x09, 0x5a, 0x07, 0x2e,
	0x3b, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_allstream_proto_rawDescOnce sync.Once
	file_allstream_proto_rawDescData = file_allstream_proto_rawDesc
)

func file_allstream_proto_rawDescGZIP() []byte {
	file_allstream_proto_rawDescOnce.Do(func() {
		file_allstream_proto_rawDescData = protoimpl.X.CompressGZIP(file_allstream_proto_rawDescData)
	})
	return file_allstream_proto_rawDescData
}

var file_allstream_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_allstream_proto_goTypes = []interface{}{
	(*StreamRequestData)(nil),  // 0: StreamRequestData
	(*StreamResponseData)(nil), // 1: StreamResponseData
}
var file_allstream_proto_depIdxs = []int32{
	0, // 0: AllStream.AllStream:input_type -> StreamRequestData
	1, // 1: AllStream.AllStream:output_type -> StreamResponseData
	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_allstream_proto_init() }
func file_allstream_proto_init() {
	if File_allstream_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_allstream_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamRequestData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_allstream_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamResponseData); 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_allstream_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_allstream_proto_goTypes,
		DependencyIndexes: file_allstream_proto_depIdxs,
		MessageInfos:      file_allstream_proto_msgTypes,
	}.Build()
	File_allstream_proto = out.File
	file_allstream_proto_rawDesc = nil
	file_allstream_proto_goTypes = nil
	file_allstream_proto_depIdxs = nil
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6

// AllStreamClient is the client API for AllStream service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AllStreamClient interface {
	AllStream(ctx context.Context, opts ...grpc.CallOption) (AllStream_AllStreamClient, error)
}

type allStreamClient struct {
	cc grpc.ClientConnInterface
}

func NewAllStreamClient(cc grpc.ClientConnInterface) AllStreamClient {
	return &allStreamClient{cc}
}

func (c *allStreamClient) AllStream(ctx context.Context, opts ...grpc.CallOption) (AllStream_AllStreamClient, error) {
	stream, err := c.cc.NewStream(ctx, &_AllStream_serviceDesc.Streams[0], "/AllStream/AllStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &allStreamAllStreamClient{stream}
	return x, nil
}

type AllStream_AllStreamClient interface {
	Send(*StreamRequestData) error
	Recv() (*StreamResponseData, error)
	grpc.ClientStream
}

type allStreamAllStreamClient struct {
	grpc.ClientStream
}

func (x *allStreamAllStreamClient) Send(m *StreamRequestData) error {
	return x.ClientStream.SendMsg(m)
}

func (x *allStreamAllStreamClient) Recv() (*StreamResponseData, error) {
	m := new(StreamResponseData)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// AllStreamServer is the server API for AllStream service.
type AllStreamServer interface {
	AllStream(AllStream_AllStreamServer) error
}

// UnimplementedAllStreamServer can be embedded to have forward compatible implementations.
type UnimplementedAllStreamServer struct {
}

func (*UnimplementedAllStreamServer) AllStream(AllStream_AllStreamServer) error {
	return status.Errorf(codes.Unimplemented, "method AllStream not implemented")
}

func RegisterAllStreamServer(s *grpc.Server, srv AllStreamServer) {
	s.RegisterService(&_AllStream_serviceDesc, srv)
}

func _AllStream_AllStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(AllStreamServer).AllStream(&allStreamAllStreamServer{stream})
}

type AllStream_AllStreamServer interface {
	Send(*StreamResponseData) error
	Recv() (*StreamRequestData, error)
	grpc.ServerStream
}

type allStreamAllStreamServer struct {
	grpc.ServerStream
}

func (x *allStreamAllStreamServer) Send(m *StreamResponseData) error {
	return x.ServerStream.SendMsg(m)
}

func (x *allStreamAllStreamServer) Recv() (*StreamRequestData, error) {
	m := new(StreamRequestData)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _AllStream_serviceDesc = grpc.ServiceDesc{
	ServiceName: "AllStream",
	HandlerType: (*AllStreamServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "AllStream",
			Handler:       _AllStream_AllStream_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
	Metadata: "allstream.proto",
}

Server

package main

import (
	"ShopBefore/rpc/grpc_all_stream/proto"
	"fmt"
	"google.golang.org/grpc"
	"log"
	"net"
	"sync"
)

type Server struct{}

func (s Server) AllStream(server proto.AllStream_AllStreamServer) error {
	// 使用协程保证接收数据和发送数据并行
	waitGroup := sync.WaitGroup{}
	waitGroup.Add(2)
	go func() {
		for {
			recv, err := server.Recv()
			if err != nil {
				log.Println(err)
				break
			}
			log.Println(recv.Data)
		}
		waitGroup.Done()
	}()
	go func() {
		i := 0
		for {
			i++
			_ = server.Send(&proto.StreamResponseData{Data: fmt.Sprintf("服务端发送信息%d", i)})
			if i > 10 {
				break
			}
		}
		waitGroup.Done()
	}()
	waitGroup.Wait()
	return nil
}

func main() {
	// 监听端口
	listen, _ := net.Listen("tcp", ":8081")
	// 创建一个grpc服务器
	server := grpc.NewServer()
	// 注册事件
	proto.RegisterAllStreamServer(server,&Server{})
	// 处理连接
	_ = server.Serve(listen)
}

// 2022/05/12 22:40:18 客户端发送消息1
// 2022/05/12 22:40:18 客户端发送消息2
// 2022/05/12 22:40:18 客户端发送消息3
// 2022/05/12 22:40:18 客户端发送消息4
// 2022/05/12 22:40:18 客户端发送消息5
// 2022/05/12 22:40:18 客户端发送消息6
// 2022/05/12 22:40:18 客户端发送消息7
// 2022/05/12 22:40:18 客户端发送消息8
// 2022/05/12 22:40:18 客户端发送消息9
// 2022/05/12 22:40:18 客户端发送消息10
// 2022/05/12 22:40:18 客户端发送消息11

Client

package main

import (
	"ShopBefore/rpc/grpc_all_stream/proto"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"sync"
)

func main() {
	// 通过grpc库建立连接
	conn, _ := grpc.Dial("localhost:8081", grpc.WithTransportCredentials(insecure.NewCredentials()))
	// 通过连接生成一个client
	client := proto.NewAllStreamClient(conn)
	// 使用协程保证接收数据和发送数据并行
	waitGroup := sync.WaitGroup{}
	waitGroup.Add(2)
	stream, _ := client.AllStream(context.Background())
	go func() {
		i := 0
		for {
			i++
			_ = stream.Send(&proto.StreamRequestData{Data: fmt.Sprintf("客户端发送消息%d", i)})
			if i > 10 {
				break
			}
		}
		waitGroup.Done()
	}()
	go func() {
		for {
			recv, err := stream.Recv()
			if err != nil {
				break
			}
			log.Println(recv.Data)
		}
		waitGroup.Done()
	}()
	waitGroup.Wait()
}

// 2022/05/12 22:40:18 服务端发送信息1
// 2022/05/12 22:40:18 服务端发送信息2
// 2022/05/12 22:40:18 服务端发送信息3
// 2022/05/12 22:40:18 服务端发送信息4
// 2022/05/12 22:40:18 服务端发送信息5
// 2022/05/12 22:40:18 服务端发送信息6
// 2022/05/12 22:40:18 服务端发送信息7
// 2022/05/12 22:40:18 服务端发送信息8
// 2022/05/12 22:40:18 服务端发送信息9
// 2022/05/12 22:40:18 服务端发送信息10
// 2022/05/12 22:40:18 服务端发送信息11

只是想理解一下grpc中的双向数据流调用,对代码中的部分error都没有进行处理.

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.番茄炒蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值