本文整理汇总了Golang中net/rpc/jsonrpc.NewClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClient函数的具体用法?Golang NewClient怎么用?Golang NewClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClient函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDiscoveryIgnore
func TestDiscoveryIgnore(t *testing.T) {
server := NewServer()
go server.processEvents()
disc := initDiscoveryTest(server, 0)
_, write := net.Pipe()
disc.client = jsonrpc.NewClient(write)
disc.Watch("group", &Void{})
if server.watchers["group"] == nil || !server.watchers["group"][disc.client] {
t.Error("Watcher not registered")
}
disc.Ignore("diff_group", &Void{})
if server.watchers["group"] == nil || !server.watchers["group"][disc.client] {
t.Error("Watcher removed")
}
otherClient := initDiscoveryTest(server, 1)
otherClient.client = jsonrpc.NewClient(write)
otherClient.Watch("group", &Void{})
if len(server.watchers["group"]) != 2 {
t.Error("Wrong watcher count")
}
disc.Ignore("group", &Void{})
if len(server.watchers["group"]) != 1 {
t.Error("Watcher was not removed")
}
otherClient.Ignore("group", &Void{})
if server.watchers["group"] != nil {
t.Error("Watcher group not deleted")
}
}
示例2: main
func main() {
client, err := net.Dial("tcp", "127.0.0.1:1234")
if err != nil {
log.Fatal("dialing:", err)
}
// Synchronous call
if len(os.Args) > 2 {
fmt.Println("StockSymbol:Percentage", os.Args[1])
fmt.Println("budget amount:", os.Args[2])
w := strings.FieldsFunc(os.Args[1], func(r rune) bool {
switch r {
case ',', ':', '%':
return true
}
return false
})
names := []string{}
num := []string{}
for i := 0; i < len(w); i = i + 2 {
names = append(names, w[i])
}
for i := 1; i < len(w); i = i + 2 {
num = append(num, w[i])
}
str2 := append(names, num...)
b, _ := strconv.ParseFloat(os.Args[2], 64)
request := Request{
NameandPercentage: str2,
Budget: b,
}
var reply Response
c := jsonrpc.NewClient(client)
err = c.Call("Responses.BuyStock", request, &reply)
if err != nil {
log.Fatal("arith error:", err)
} else {
fmt.Println("TradeID:", reply.TradeId)
fmt.Println("stock details:", reply.Stocks)
fmt.Println("unvested amount:", reply.Unvested)
}
} else {
var reply1 Check
c1 := jsonrpc.NewClient(client)
c, _ := strconv.ParseInt(os.Args[1], 10, 64)
err = c1.Call("Checks.Checkprice", c, &reply1)
if err != nil {
log.Fatal("arith error:", err)
} else {
fmt.Println("stock details:", reply1.Stocks)
fmt.Println("current market value:", reply1.Currentmarketvalue)
fmt.Println("unvested amount:", reply1.Unvested)
}
}
}
示例3: main
func main() {
client, err := net.Dial("tcp", "127.0.0.1:1234")
if err != nil {
log.Fatal("dialing:", err)
}
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter Stock Symbol: ")
StockSymbolAndPercentage, _ := reader.ReadString('\n')
fmt.Println(StockSymbolAndPercentage)
fmt.Print("Enter budget: ")
var UserBudget float64
fmt.Scan(&UserBudget)
args := Args{StockSymbolAndPercentage, UserBudget}
var quo Quote
c := jsonrpc.NewClient(client)
err = c.Call("StockCalc.StockPrice", args, &quo)
if err != nil {
log.Fatal("arith error:", err)
}
f, _ := strconv.ParseFloat("quo.Stocks", 64)
fmt.Println("TradeID:", quo.TradeId)
fmt.Println("Stocks", quo.Stocks)
fmt.Println("Remaining amount", quo.UnvestedAmount)
client, err = net.Dial("tcp", "127.0.0.1:1234")
if err != nil {
log.Fatal("dialing:", err)
}
fmt.Println("\nEnter Trade Id")
var s int
fmt.Scan(&s)
if s == 1 {
args := Args{StockSymbolAndPercentage, UserBudget}
var quo Quote
c := jsonrpc.NewClient(client)
err = c.Call("StockCalc.StockPrice", args, &quo)
if err != nil {
log.Fatal("error:", err)
}
x, _ := strconv.ParseFloat("quo.Stocks", 64)
y := x - f
fmt.Println("Stocks:", quo.Stocks)
fmt.Println("Profit/Loss per stock:", y)
fmt.Println("Uninvested amount:", quo.UnvestedAmount)
}
}
示例4: fillRpcClient
func (c *Client) fillRpcClient(conn net.Conn) {
switch c.encodingType {
case EncodingTypeJson:
c.Client = jsonrpc.NewClient(conn)
case EncodingTypeMsgpack:
rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, new(codec.MsgpackHandle))
c.Client = rpc.NewClientWithCodec(rpcCodec)
case EncodingTypeGob:
c.Client = rpc.NewClient(conn)
default:
c.Client = jsonrpc.NewClient(conn)
}
}
示例5: TestDiscoveryWatch
func TestDiscoveryWatch(t *testing.T) {
server := NewServer()
go server.processEvents()
disc := initDiscoveryTest(server, 0)
err := disc.Watch("group", &Void{})
if err == nil {
t.Error("Watching without a client should fail")
}
if disc.client != nil {
t.Error()
}
_, ok := server.watchers["group"]
if ok {
t.Error("Watcher should not be added")
}
_, write := net.Pipe()
disc.client = jsonrpc.NewClient(write)
err = disc.Watch("group", &Void{})
if err != nil {
t.Error(err)
}
if !server.watchers["group"][disc.client] {
t.Error("Watcher not added")
}
}
示例6: DialTimeout
func DialTimeout(network, address string, timeout time.Duration) (*rpc.Client, error) {
conn, err := net.DialTimeout(network, address, timeout)
if err != nil {
return nil, err
}
return jsonrpc.NewClient(conn), err
}
示例7: BenchmarkJSONRPC_pipe
func BenchmarkJSONRPC_pipe(b *testing.B) {
cli, srv := net.Pipe()
go jsonrpc.ServeConn(srv)
client := jsonrpc.NewClient(cli)
defer client.Close()
benchmarkRPC(b, client)
}
示例8: doRequests
func doRequests(conn net.Conn) {
fmt.Println("start doRequests")
jsonRpcClient := jsonrpc.NewClient(conn)
for {
fmt.Println("waiting for okay to go")
var mySStr string
fmt.Scanln(&mySStr)
fmt.Println("go")
var pong string
go func() {
var test *UdevStr
test = new(UdevStr)
test.Blub = "hallo"
test.Test = "test"
err := jsonRpcClient.Call("Servable.Ping", "HI TEHERE", &pong) // "hi there"
if err != nil {
//fail
fmt.Errorf("Could not ping/pong PredReplace", err)
return
}
fmt.Println("Ping pong:" + pong)
}()
}
fmt.Println("end doRequests")
}
示例9: PushHandler
func PushHandler(ws *websocket.Conn) {
//log.Println("connection websocket on pushHandler")
var c *connection
// Looking for an existing key
key := readKey(ws)
if len(key) > 0 && h.keyExists(key) {
// Key exists => get connection
c = h.connections[key]
} else {
// No key or key doesn't exists => creating a new connection
rc := jsonrpc.NewClient(ws)
key = h.generateKey()
user := &users.User{
Token: key,
}
call := make(chan *RpcCall, 100)
c = &connection{
ws: ws,
rc: rc,
user: user,
call: call,
}
}
c.ws = ws
// Registering the connection
h.register <- c
c.callPump()
}
示例10: dialRpcClient
// Create a new client
func dialRpcClient(servAddr string, portNo uint16) (*rpc.Client, net.Conn) {
var client *rpc.Client
var conn net.Conn
var err error
log.Infof("Connecting to RPC server: %s:%d", servAddr, portNo)
// Retry connecting for 10sec
for i := 0; i < 10; i++ {
// Connect to the server
conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", servAddr, portNo))
if err == nil {
log.Infof("Connected to RPC server: %s:%d", servAddr, portNo)
// Create an RPC client
client = jsonrpc.NewClient(conn)
break
}
log.Warnf("Error %v connecting to %s:%s. Retrying..", err, servAddr, portNo)
// Sleep for a second and retry again
time.Sleep(1 * time.Second)
}
// If we failed to connect, report error
if client == nil {
log.Errorf("Failed to connect to Rpc server %s:%d", servAddr, portNo)
return nil, nil
}
return client, conn
}
示例11: DialJsonRpc
func DialJsonRpc(network, address, path string) (*rpc.Client, error) {
var err error
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
io.WriteString(conn, "CONNECT "+path+" HTTP/1.0\n\n")
// Require successful HTTP response
// before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})
if err == nil && resp.Status == jsonRpcConnected {
return jsonrpc.NewClient(conn), nil
}
if err == nil {
err = errors.New("unexpected HTTP response: " + resp.Status)
}
conn.Close()
return nil, &net.OpError{
Op: "dial-http",
Net: network + " " + address,
Addr: nil,
Err: err,
}
}
示例12: InternalStatus
func InternalStatus(c *cli.Context) {
filename := CONFIG_FILENAME
if c.String("filename") != "" {
filename = c.String("filename")
}
configuration := cfg.Setup(filename)
address := fmt.Sprintf("%s:%d",
configuration.GeneralConfig.RPCHost,
configuration.GeneralConfig.RPCPort,
)
log.Println("Start SSLB (Client) ")
client, err := net.Dial("tcp", address)
if err != nil {
log.Fatal(err)
}
reply := sslbRPC.StatusResponse{}
rpcCall := jsonrpc.NewClient(client)
err = rpcCall.Call("ServerStatus.GetIdle", 0, &reply)
if err != nil {
log.Fatal(err)
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Workers Idle"})
idles := fmt.Sprintf("%d", reply.IdleWPool)
table.Append([]string{idles})
table.Render()
}
示例13: TestRPC
func TestRPC(t *testing.T) {
message := "Echo"
rpcServer, err := NewRPCServer(addr, provideCodec, &RPCImpl{}, nil, nil)
if err != nil {
log.Fatalf("Can not create RPC server: %s", err.Error())
}
err = rpcServer.Start()
if err != nil {
log.Fatalf("Can not start RPC server: %s", err.Error())
}
conn, err := net.Dial("tcp", addr)
if err != nil {
log.Fatalf("Can not connect to RPC server: %s", err.Error())
}
client := jsonrpc.NewClient(conn)
var out string
err = client.Call("RPCImpl.Echo", message, &out)
if err != nil {
log.Fatalf("Can not execute RPC: %s", err.Error())
}
if out != message {
log.Fatalf("Expected message %s, got %s", message, out)
}
log.Printf("Got echo: %s", out)
rpcServer.Stop()
}
示例14: DialHTTP
func DialHTTP(network, address, path string) (*rpc.Client, error) {
var err error
conn, err := net.Dial(network, address)
if err != nil {
return nil, err
}
io.WriteString(conn, "GET "+path+" HTTP/1.1\n\n")
// Require successful HTTP response
// before switching to RPC protocol.
resp, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err == nil {
if resp.Status == jsonRpcConnected {
return jsonrpc.NewClient(conn), nil
}
}
conn.Close()
return nil, &net.OpError{
Op: "JsonRPC dial to",
Net: network + "://" + address,
Err: errors.New("unexpected HTTP response: " + resp.Status),
}
}
示例15: Client
func Client() {
var err error
var c net.Conn
c, err = net.DialTimeout("tcp", "127.0.0.1:1234", 1000*1000*1000*30)
if err != nil {
log.Fatal("dialing:", err)
}
var client *rpc.Client
client = jsonrpc.NewClient(c)
// 同步
var args *Args = &Args{7, 8}
var reply *Data = new(Data)
client.Call("Arith.Plus", args, reply)
fmt.Println(reply)
// 异步
args.A = 1
args.B = 2
var call *rpc.Call
call = client.Go("Arith.Plus", args, reply, nil)
var doneCall *rpc.Call
doneCall = <-call.Done
fmt.Println(doneCall.Args, doneCall.Reply)
fmt.Println(args, reply)
client.Close()
c.Close()
}