golang grpc服务端客户端简单源码实现

前端之家收集整理的这篇文章主要介绍了golang grpc服务端客户端简单源码实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

协议

hello.proto 文件

Syntax = "proto3";
package hello;
 
message HelloRequest {
string greeting = 1;
}
 
message HelloResponse {
string reply = 1;
repeated int32 number = 4;
}
 
service HelloService {
rpc SayHello(HelloRequest) returns (HelloResponse) {}
}

服务端代码

// test_grpc project test_grpc.go
package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	pb "proto"

	context "golang.org/x/net/context"
	"google.golang.org/grpc"
)

type server struct{}

func (s *server) SayHello(ctx context.Context,in *pb.HelloRequest) (*pb.HelloResponse,error) {
	//fmt.Println("hello")
	if in.Greeting == "helloworld" {
		return &pb.HelloResponse{in.Greeting,[]int32{1,2}},nil
	} else {
		return &pb.HelloResponse{"fjgui",[]int32{666}},nil
	}
	//return &pb.HelloResponse{"fjgui",nil
}

func main() {
	port := flag.Int("port",8000,"the server")
	lis,err := net.Listen("tcp",fmt.Sprintf("127.0.0.1:%d",*port))
	if err != nil {
		log.Fatalf("Failed to listen: %v",err)
	}

	s := grpc.NewServer()
	pb.RegisterHelloServiceServer(s,&server{})
	s.Serve(lis)
}
客户端代码
// test_grpc_client project test_grpc_client.go
package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	pb "proto"

	context "golang.org/x/net/context"
	"google.golang.org/grpc"
)

func main() {
	address := flag.String("addressfjgui","127.0.0.1:8000","The server address in the format of host:port")
	conn,err := grpc.Dial(*address,grpc.WithInsecure())
	if err != nil {
		log.Fatalf("did not connect:%v",err)
	}

	defer conn.Close()
	c := pb.NewHelloServiceClient(conn)

	req_greeting := "helloworld"
	if len(os.Args) > 1 {
		req_greeting = os.Args[1]
	}

	r,err := c.SayHello(context.Background(),&pb.HelloRequest{req_greeting})
	fmt.Println(req_greeting)
	if err != nil {
		log.Fatalf("could not greet: %v",err)
	}
	log.Printf("Greeting: %v",r.Reply)
	log.Printf("Greeting: %v",r.Number)
}

猜你在找的Go相关文章