golang 实现 · PHP/Python/前端/Linux 等等 学习笔记 · 看云
[TOC]
## 目录
```
├── base
│ └── struct.go
├── client.go
├── pr
│ └── helloword.proto
└── server.go
```
<details>
<summary>base/struct.go
</summary>
```
package base
import (
"context"
"grpc/demo/pr"
)
type Server struct{}
func (s *Server) SayHello(ctx context.Context, in *pr.HelloRequest) (*pr.HelloReply, error) {
return &pr.HelloReply{Message: "Hello " + in.Name}, nil
}
```
</details>
<br/>
<details>
<summary>client.go
</summary>
```
package main
import (
"context"
"grpc/demo/pr"
"log"
"google.golang.org/grpc"
)
const (
address = "127.0.0.1:50051"
)
var input =make(chan string )
func main() {
// Set up a connection to the server.
conn, err := grpc.Dial(address,grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pr.NewGreeterClient(conn)
r, err := c.SayHello(context.Background(), &pr.HelloRequest{Name:"cc"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.Message)
}
```
</details>
<br/>
<details>
<summary>server.go</summary>
```
package main
import (
"grpc/demo/base"
"grpc/demo/pr"
"log"
"net"
"google.golang.org/grpc"
)
const (
port = ":50051"
)
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pr.RegisterGreeterServer(s, &base.Server{})
err = s.Serve(lis)
if err != nil {
log.Printf("%v",err)
}
}
```
</details>
<br/>
<details>
<summary>server.go</summary>
```
package main
import (
"grpc/demo/base"
"grpc/demo/pr"
"log"
"net"
"google.golang.org/grpc"
)
const (
port = ":50051"
)
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pr.RegisterGreeterServer(s, &base.Server{})
err = s.Serve(lis)
if err != nil {
log.Printf("%v",err)
}
}
```
</details>
<br/>
## proto 转go
```
go mod grpc/demo
cd pr
protoc --go_out=plugins=grpc:. helloword.proto
cd ../
go run server.go
go run client.go
```