You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

  1. package core_grpc
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. "time"
  7. "golang.org/x/net/netutil"
  8. "google.golang.org/grpc"
  9. cmn "github.com/tendermint/tendermint/libs/common"
  10. )
  11. // Config is an gRPC server configuration.
  12. type Config struct {
  13. MaxOpenConnections int
  14. }
  15. // StartGRPCServer starts a new gRPC BroadcastAPIServer, listening on
  16. // protoAddr, in a goroutine. Returns a listener and an error, if it fails to
  17. // parse an address.
  18. func StartGRPCServer(protoAddr string, config Config) (net.Listener, error) {
  19. parts := strings.SplitN(protoAddr, "://", 2)
  20. if len(parts) != 2 {
  21. return nil, fmt.Errorf("Invalid listen address for grpc server (did you forget a tcp:// prefix?) : %s", protoAddr)
  22. }
  23. proto, addr := parts[0], parts[1]
  24. ln, err := net.Listen(proto, addr)
  25. if err != nil {
  26. return nil, err
  27. }
  28. if config.MaxOpenConnections > 0 {
  29. ln = netutil.LimitListener(ln, config.MaxOpenConnections)
  30. }
  31. grpcServer := grpc.NewServer()
  32. RegisterBroadcastAPIServer(grpcServer, &broadcastAPI{})
  33. go grpcServer.Serve(ln) // nolint: errcheck
  34. return ln, nil
  35. }
  36. // StartGRPCClient dials the gRPC server using protoAddr and returns a new
  37. // BroadcastAPIClient.
  38. func StartGRPCClient(protoAddr string) BroadcastAPIClient {
  39. conn, err := grpc.Dial(protoAddr, grpc.WithInsecure(), grpc.WithDialer(dialerFunc))
  40. if err != nil {
  41. panic(err)
  42. }
  43. return NewBroadcastAPIClient(conn)
  44. }
  45. func dialerFunc(addr string, timeout time.Duration) (net.Conn, error) {
  46. return cmn.Connect(addr)
  47. }