tendermint/rpc/grpc/client_server.go

57 lines
1.4 KiB
Go
Raw Normal View History

2016-06-21 10:19:49 -07:00
package core_grpc
import (
"fmt"
"net"
"strings"
"time"
"golang.org/x/net/netutil"
2016-06-21 10:19:49 -07:00
"google.golang.org/grpc"
2017-10-04 13:40:45 -07:00
cmn "github.com/tendermint/tmlibs/common"
2016-06-21 10:19:49 -07:00
)
// Config is an gRPC server configuration.
type Config struct {
MaxOpenConnections int
}
// StartGRPCServer starts a new gRPC BroadcastAPIServer, listening on
// protoAddr, in a goroutine. Returns a listener and an error, if it fails to
// parse an address.
func StartGRPCServer(protoAddr string, config Config) (net.Listener, error) {
2016-06-21 10:19:49 -07:00
parts := strings.SplitN(protoAddr, "://", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("Invalid listen address for grpc server (did you forget a tcp:// prefix?) : %s", protoAddr)
}
proto, addr := parts[0], parts[1]
ln, err := net.Listen(proto, addr)
if err != nil {
return nil, err
}
if config.MaxOpenConnections > 0 {
ln = netutil.LimitListener(ln, config.MaxOpenConnections)
}
2016-06-21 10:19:49 -07:00
grpcServer := grpc.NewServer()
RegisterBroadcastAPIServer(grpcServer, &broadcastAPI{})
2017-10-03 15:49:20 -07:00
go grpcServer.Serve(ln) // nolint: errcheck
2016-06-21 10:19:49 -07:00
return ln, nil
}
// StartGRPCClient dials the gRPC server using protoAddr and returns a new
// BroadcastAPIClient.
2016-06-21 10:19:49 -07:00
func StartGRPCClient(protoAddr string) BroadcastAPIClient {
conn, err := grpc.Dial(protoAddr, grpc.WithInsecure(), grpc.WithDialer(dialerFunc))
if err != nil {
panic(err)
}
return NewBroadcastAPIClient(conn)
}
func dialerFunc(addr string, timeout time.Duration) (net.Conn, error) {
2017-10-04 13:40:45 -07:00
return cmn.Connect(addr)
2016-06-21 10:19:49 -07:00
}