2025-02-16 17:30:04 +08:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2025-02-16 18:13:10 +08:00
|
|
|
"io"
|
|
|
|
"time"
|
2025-02-16 17:30:04 +08:00
|
|
|
|
|
|
|
"gitlab.com/go-course-project/go17/skills/grpc/service"
|
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// Deprecated: use WithTransportCredentials and insecure.NewCredentials()
|
|
|
|
// instead. Will be supported throughout 1.x.
|
2025-03-02 14:27:57 +08:00
|
|
|
conn, err := grpc.NewClient("localhost:18080", grpc.WithTransportCredentials(insecure.NewCredentials()))
|
2025-02-16 17:30:04 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
client := service.NewHelloServiceClient(conn)
|
2025-02-16 18:13:10 +08:00
|
|
|
// resp, err := client.Hello(context.Background(), &service.HelloRequest{
|
|
|
|
// MyName: "bob",
|
|
|
|
// })
|
|
|
|
// if err != nil {
|
|
|
|
// panic(err)
|
|
|
|
// }
|
|
|
|
// fmt.Println(resp)
|
|
|
|
|
|
|
|
stream, err := client.Chat(context.Background())
|
2025-02-16 17:30:04 +08:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2025-02-16 18:13:10 +08:00
|
|
|
|
|
|
|
// 1. 处理返回结果的在后台
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
resp, err := stream.Recv()
|
|
|
|
if err != nil {
|
|
|
|
// 如果遇到io.EOF表示客户端流被关闭
|
|
|
|
if err == io.EOF {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
fmt.Println(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
fmt.Println(resp)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// 2. 发送请求的在主Goroutine
|
|
|
|
for i := range 10 {
|
|
|
|
stream.Send(&service.ChatRequest{
|
|
|
|
Id: uint64(i + 1),
|
|
|
|
Message: "test",
|
|
|
|
})
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
}
|
2025-02-16 17:30:04 +08:00
|
|
|
}
|