1. 安装grpc
go get -u google.golang.org/grpc
2. 服务端 server
package main
import (
"context"
"fmt"
"github.com/youzeliang/gopractice/grpcfor/example"
"google.golang.org/grpc"
"log"
"net"
"strconv"
)
var times = 0
type service struct {
}
func (s *service) HelloWorld(ctx context.Context, in *example.HelloRequest) (*example.HelloReply, error) {
log.Printf("Received: %v", in.Name)
times++
return &example.HelloReply{Message: "Hello 您好!" + in.Name+" 您是今天第"+strconv.Itoa(times)+"个访客"}, nil
}
func main() {
conn, err := net.Listen("tcp", "127.0.0.1:9999")
fmt.Println(conn, err)
server := grpc.NewServer()
example.RegisterHelloServer(server, &service{})
//读取请求并响应
err = server.Serve(conn)
if err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
3. 客户端
package main
import (
"context"
"google.golang.org/grpc"
"log"
"os"
pb "github.com/youzeliang/gopractice/grpcfor/example"
"time"
)
func main() {
//连接服务端句柄
//WithInsecure()不指定安全选项
conn, err := grpc.Dial("127.0.0.1:9999", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
cli := pb.NewHelloClient(conn)
name := "XXGH"
//获取命令行参数
if len(os.Args) > 1 {
name = os.Args[1]
}
//设置上下文超时
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
//响应
resp, err := cli.HelloWorld(ctx, &pb.HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not succ: %v", err)
}
log.Printf("Receive from server: %s", resp.Message)
}