103 lines
2.7 KiB
Go
103 lines
2.7 KiB
Go
package token
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"time"
|
|
|
|
pb "schain/proto"
|
|
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/credentials/insecure"
|
|
"google.golang.org/grpc/keepalive"
|
|
)
|
|
|
|
const (
|
|
dialTimeout = 10 * time.Second
|
|
maxRecvMessageSize = 100 * 1024 * 1024 // 100 MiB
|
|
maxSendMessageSize = 100 * 1024 * 1024 // 100 MiB
|
|
|
|
)
|
|
|
|
// 建立与grpc服务器的连接
|
|
func NewClient(address string) (*grpc.ClientConn, error) {
|
|
var conn *grpc.ClientConn
|
|
//Keepalive 时间、超时时间和允许无流的连接
|
|
kaOpts := keepalive.ClientParameters{
|
|
Time: 1 * time.Minute,
|
|
Timeout: 20 * time.Second,
|
|
PermitWithoutStream: true,
|
|
}
|
|
|
|
//gRPC 连接选项
|
|
dialOpts := []grpc.DialOption{
|
|
grpc.WithKeepaliveParams(kaOpts),
|
|
grpc.WithBlock(),
|
|
grpc.FailOnNonTempDialError(true),
|
|
grpc.WithDefaultCallOptions(
|
|
grpc.MaxCallRecvMsgSize(maxRecvMessageSize),
|
|
grpc.MaxCallSendMsgSize(maxSendMessageSize),
|
|
),
|
|
}
|
|
//取消证书认证
|
|
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
|
|
|
//ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
|
|
//defer cancel()
|
|
conn, err := grpc.Dial(address, dialOpts...)
|
|
//conn, err := grpc.DialContext(ctx, address, dialOpts...)
|
|
if err != nil {
|
|
log.Fatalf("did not connect: %s", err)
|
|
}
|
|
|
|
//调用服务器上的 Login RPC 方法
|
|
client := pb.NewPingClient(conn)
|
|
|
|
//对username和password进行aes加密
|
|
usr, err := encrypt("Wuxinyu", key)
|
|
if err != nil {
|
|
panic("encrypt error")
|
|
}
|
|
pwd, err := encrypt("123456", key)
|
|
if err != nil {
|
|
panic("encrypt error")
|
|
}
|
|
loginReply, err := client.Login(context.Background(), &pb.LoginRequest{Username: usr, Password: pwd})
|
|
if err != nil {
|
|
log.Fatalf("Error when calling SayHello: %s", err)
|
|
panic("wrong")
|
|
}
|
|
fmt.Println("Login Reply:", loginReply)
|
|
conn.Close()
|
|
|
|
//Call SayHello,第二次连接
|
|
requestToken := new(AuthToken)
|
|
requestToken.Token = loginReply.Token
|
|
|
|
//创建一个超时的上下文连接
|
|
ctx, cancel := context.WithTimeout(context.Background(), dialTimeout)
|
|
defer cancel()
|
|
dialOpts = append(dialOpts, grpc.WithPerRPCCredentials(requestToken))
|
|
conn, err = grpc.DialContext(ctx, address, dialOpts...)
|
|
if err != nil {
|
|
log.Fatalf("did not connect: %s", err)
|
|
}
|
|
|
|
client = pb.NewPingClient(conn)
|
|
|
|
helloreply, err := client.SayHello(context.Background(), &pb.PingMessage{Greeting: "foo"})
|
|
if err != nil {
|
|
log.Fatalf("Error when calling SayHello: %s", err)
|
|
panic("connect error")
|
|
}
|
|
log.Printf("Response from server: %s", helloreply.Greeting)
|
|
|
|
//通过验证,返回客户端连接
|
|
return conn, err
|
|
}
|
|
|
|
func NewRegisterClient(conn *grpc.ClientConn) (pb.ChaincodeSupportClient, error) {
|
|
return pb.NewChaincodeSupportClient(conn), nil
|
|
}
|