简单模式:简单模式只是使用参数和返回值作为服务器与客户端传递数据的方式
实际编码在定义服务时:入参什么也不要加
// The service definition.
service ToUpper{
rpc Upper (UpperRequest) returns (UpperReply) {}
}
syntax="proto3";
package proto;
// The request message
message UpperRequest {
string name = 1;
}
// The response message
message UpperReply {
string message = 1;
}
// The service definition.
service ToUpper{
// Sends a greeting
rpc Upper (UpperRequest) returns (UpperReply) {}
}
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.21.0
// protoc v3.6.1
// source: jiandanmushi.proto
package proto
import (
context "context"
proto "github.com/golang/protobuf/proto"
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)
)
// This is a compile-time assertion that a sufficiently up-to-date version
// of the legacy proto package is being used.
const _ = proto.ProtoPackageIsVersion4
// The request message
type UpperRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
}
func (x *UpperRequest) Reset() {
*x = UpperRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_jiandanmushi_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UpperRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpperRequest) ProtoMessage() {}
func (x *UpperRequest) ProtoReflect() protoreflect.Message {
mi := &file_jiandanmushi_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 UpperRequest.ProtoReflect.Descriptor instead.
func (*UpperRequest) Descriptor() ([]byte, []int) {
return file_jiandanmushi_proto_rawDescGZIP(), []int{0}
}
func (x *UpperRequest) GetName() string {
if x != nil {
return x.Name
}
return ""
}
// The response message
type UpperReply struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"`
}
func (x *UpperReply) Reset() {
*x = UpperReply{}
if protoimpl.UnsafeEnabled {
mi := &file_jiandanmushi_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *UpperReply) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpperReply) ProtoMessage() {}
func (x *UpperReply) ProtoReflect() protoreflect.Message {
mi := &file_jiandanmushi_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 UpperReply.ProtoReflect.Descriptor instead.
func (*UpperReply) Descriptor() ([]byte, []int) {
return file_jiandanmushi_proto_rawDescGZIP(), []int{1}
}
func (x *UpperReply) GetMessage() string {
if x != nil {
return x.Message
}
return ""
}
var File_jiandanmushi_proto protoreflect.FileDescriptor
var file_jiandanmushi_proto_rawDesc = []byte{
0x0a, 0x12, 0x6a, 0x69, 0x61, 0x6e, 0x64, 0x61, 0x6e, 0x6d, 0x75, 0x73, 0x68, 0x69, 0x2e, 0x70,
0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x22, 0x0a, 0x0c, 0x55,
0x70, 0x70, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x12, 0x0a, 0x04, 0x6e,
0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x22,
0x26, 0x0a, 0x0a, 0x55, 0x70, 0x70, 0x65, 0x72, 0x52, 0x65, 0x70, 0x6c, 0x79, 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, 0x32, 0x3c, 0x0a, 0x07, 0x54, 0x6f, 0x55, 0x70, 0x70,
0x65, 0x72, 0x12, 0x31, 0x0a, 0x05, 0x55, 0x70, 0x70, 0x65, 0x72, 0x12, 0x13, 0x2e, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x2e, 0x55, 0x70, 0x70, 0x65, 0x72, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74,
0x1a, 0x11, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2e, 0x55, 0x70, 0x70, 0x65, 0x72, 0x52, 0x65,
0x70, 0x6c, 0x79, 0x22, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}
var (
file_jiandanmushi_proto_rawDescOnce sync.Once
file_jiandanmushi_proto_rawDescData = file_jiandanmushi_proto_rawDesc
)
func file_jiandanmushi_proto_rawDescGZIP() []byte {
file_jiandanmushi_proto_rawDescOnce.Do(func() {
file_jiandanmushi_proto_rawDescData = protoimpl.X.CompressGZIP(file_jiandanmushi_proto_rawDescData)
})
return file_jiandanmushi_proto_rawDescData
}
var file_jiandanmushi_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_jiandanmushi_proto_goTypes = []interface{}{
(*UpperRequest)(nil), // 0: proto.UpperRequest
(*UpperReply)(nil), // 1: proto.UpperReply
}
var file_jiandanmushi_proto_depIdxs = []int32{
0, // 0: proto.ToUpper.Upper:input_type -> proto.UpperRequest
1, // 1: proto.ToUpper.Upper:output_type -> proto.UpperReply
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_jiandanmushi_proto_init() }
func file_jiandanmushi_proto_init() {
if File_jiandanmushi_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_jiandanmushi_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UpperRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_jiandanmushi_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*UpperReply); 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_jiandanmushi_proto_rawDesc,
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_jiandanmushi_proto_goTypes,
DependencyIndexes: file_jiandanmushi_proto_depIdxs,
MessageInfos: file_jiandanmushi_proto_msgTypes,
}.Build()
File_jiandanmushi_proto = out.File
file_jiandanmushi_proto_rawDesc = nil
file_jiandanmushi_proto_goTypes = nil
file_jiandanmushi_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
// ToUpperClient is the client API for ToUpper service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ToUpperClient interface {
// Sends a greeting
Upper(ctx context.Context, in *UpperRequest, opts ...grpc.CallOption) (*UpperReply, error)
}
type toUpperClient struct {
cc grpc.ClientConnInterface
}
func NewToUpperClient(cc grpc.ClientConnInterface) ToUpperClient {
return &toUpperClient{cc}
}
func (c *toUpperClient) Upper(ctx context.Context, in *UpperRequest, opts ...grpc.CallOption) (*UpperReply, error) {
out := new(UpperReply)
err := c.cc.Invoke(ctx, "/proto.ToUpper/Upper", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// ToUpperServer is the server API for ToUpper service.
type ToUpperServer interface {
// Sends a greeting
Upper(context.Context, *UpperRequest) (*UpperReply, error)
}
// UnimplementedToUpperServer can be embedded to have forward compatible implementations.
type UnimplementedToUpperServer struct {
}
func (*UnimplementedToUpperServer) Upper(context.Context, *UpperRequest) (*UpperReply, error) {
return nil, status.Errorf(codes.Unimplemented, "method Upper not implemented")
}
func RegisterToUpperServer(s *grpc.Server, srv ToUpperServer) {
s.RegisterService(&_ToUpper_serviceDesc, srv)
}
func _ToUpper_Upper_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpperRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(ToUpperServer).Upper(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/proto.ToUpper/Upper",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(ToUpperServer).Upper(ctx, req.(*UpperRequest))
}
return interceptor(ctx, in, info, handler)
}
var _ToUpper_serviceDesc = grpc.ServiceDesc{
ServiceName: "proto.ToUpper",
HandlerType: (*ToUpperServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Upper",
Handler: _ToUpper_Upper_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "jiandanmushi.proto",
}
服务侧代码:
package main
import (
"log"
"net"
// "strings"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "jidanmoshi/proto"
"google.golang.org/grpc/reflection"
)
const (
port = ":8089"
)
type server struct{}
/*接口定义,可以粘贴复制proto文件中的*/
/*
// ToUpperServer is the server API for ToUpper service.
type ToUpperServer interface {
// Sends a greeting
Upper(context.Context, *UpperRequest) (*UpperReply, error)
}
*/
func (s *server) Upper(ctx context.Context, in *pb.UpperRequest) (*pb.UpperReply, error) {
log.Printf("Received: %s", in.Name) //服务器侧收到strings 类型的数据
a :="LSL:"
return &pb.UpperReply{Message: a + in.Name}, nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterToUpperServer(s, &server{}) //注册服务
// Register reflection service on gRPC server.
reflection.Register(s)
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
客户端代码:
package main
import (
"log"
"os"
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "jidanmoshi/proto"
)
const (
address = "localhost:8089"
)
func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address, grpc.WithInsecure()) //无认证方式
if err != nil {
log.Fatalf("error! not connect: %v", err)
}
defer conn.Close() //延迟,防止未关闭连接
c := pb.NewToUpperClient(conn)
// Contact the server and print out its response.
name := "nihao"
if len(os.Args) > 1 {
name = os.Args[1] //赋值
}
/*调用约定好的服务接口,体现了平台中立思想,就是因为之前生成的proto文件*/
r, err := c.Upper(context.Background(), &pb.UpperRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
fmt.Printf("Response: %s", r.Message)
}