75 lines
1.2 KiB
Go
75 lines
1.2 KiB
Go
package rpcsup
|
|
|
|
import (
|
|
"context"
|
|
"dashboard/logger"
|
|
"errors"
|
|
"net"
|
|
"net/rpc"
|
|
"net/rpc/jsonrpc"
|
|
|
|
"golang.org/x/sync/errgroup"
|
|
)
|
|
|
|
func JsonServer(ctx context.Context, log *logger.Logger, address string, service ...interface{}) error {
|
|
for _, re := range service {
|
|
if err := rpc.Register(re); err != nil {
|
|
log.Sugar().Error(err)
|
|
return err
|
|
}
|
|
}
|
|
|
|
listen, err := net.Listen("tcp", address)
|
|
if err != nil {
|
|
log.Sugar().Error(err)
|
|
return err
|
|
}
|
|
|
|
log.Sugar().Infof("Rpc server listen on: %s", address)
|
|
|
|
wg, ctxx := errgroup.WithContext(ctx)
|
|
|
|
wg.Go(func() error {
|
|
for {
|
|
accept, err := listen.Accept()
|
|
if err != nil {
|
|
if errors.Is(err, net.ErrClosed) {
|
|
log.Sugar().Error(err)
|
|
|
|
break
|
|
}
|
|
log.Sugar().Error(err)
|
|
continue
|
|
}
|
|
|
|
go jsonrpc.ServeConn(accept)
|
|
}
|
|
|
|
return err
|
|
})
|
|
|
|
wg.Go(func() error {
|
|
<-ctxx.Done()
|
|
log.Sugar().Errorf("Unis Rpc Server cancel by ctx")
|
|
listen.Close()
|
|
return ctxx.Err()
|
|
})
|
|
|
|
if err := wg.Wait(); err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func JsonClient(log *logger.Logger, address string) (*rpc.Client, error) {
|
|
dial, err := net.Dial("tcp", address)
|
|
if err != nil {
|
|
log.Sugar().Error(err)
|
|
|
|
return nil, err
|
|
}
|
|
|
|
return jsonrpc.NewClient(dial), nil
|
|
}
|