server.go 932 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/tal-tech/go-zero/core/conf"
  6. "github.com/tal-tech/go-zero/zrpc"
  7. "github.com/zeromicro/zero-examples/rpc/remote/stream"
  8. "google.golang.org/grpc"
  9. )
  10. type StreamGreetServer int
  11. func (gs StreamGreetServer) Greet(s stream.StreamGreeter_GreetServer) error {
  12. ctx := s.Context()
  13. for {
  14. select {
  15. case <-ctx.Done():
  16. fmt.Println("cancelled by client")
  17. return ctx.Err()
  18. default:
  19. req, err := s.Recv()
  20. if err == io.EOF {
  21. return nil
  22. }
  23. if err != nil {
  24. return err
  25. }
  26. fmt.Println("=>", req.Name)
  27. greet := "hello, " + req.Name
  28. fmt.Println("<=", greet)
  29. s.Send(&stream.StreamResp{
  30. Greet: greet,
  31. })
  32. }
  33. }
  34. }
  35. func main() {
  36. var c zrpc.RpcServerConf
  37. conf.MustLoad("etc/config.json", &c)
  38. server := zrpc.MustNewServer(c, func(grpcServer *grpc.Server) {
  39. stream.RegisterStreamGreeterServer(grpcServer, StreamGreetServer(0))
  40. })
  41. server.Start()
  42. }