func main() { service := "localhost:1234" if len(os.Args) == 2 { client, err := jsonrpc.Dial("tcp", service) if err != nil { log.Fatal("dialing:", err) } var reply string err = client.Call("Stock.GetStockDetails", os.Args[1], &reply) if err != nil { log.Fatal("stock error:", err) } fmt.Println(reply) } if len(os.Args) < 2 { fmt.Println("Usage: ", os.Args[0], "server") os.Exit(1) } if len(os.Args) > 2 { client, err := jsonrpc.Dial("tcp", service) if err != nil { log.Fatal("dialing:", err) } args := Args{os.Args[1], os.Args[2]} var reply string err = client.Call("Stock.Buy", args, &reply) if err != nil { log.Fatal("stock error:", err) } fmt.Println(reply) } }
// Connect rpc client to rater func TestSMGRplcApierRpcConn(t *testing.T) { if smgRplcMstrRPC, err = jsonrpc.Dial("tcp", smgRplcMasterCfg.RPCJSONListen); err != nil { t.Fatal(err) } if smgRplcSlvRPC, err = jsonrpc.Dial("tcp", smgRplcSlaveCfg.RPCJSONListen); err != nil { t.Fatal(err) } }
func main() { var i int fmt.Println("Put 1 to purchase stocks, 2 to check portfolio, anything else to exit") fmt.Scanf("%d", &i) switch i { case 1: fmt.Println("Enter Stock Key & Stock Percentage(E.g. “GOOG:50%,YHOO:50%”)") var input string fmt.Scanln(&input) fmt.Println("Enter Your Budget") var budget float32 fmt.Scanln(&budget) client, err := jsonrpc.Dial("tcp", ":1234") if err != nil { log.Fatal("dialing:", err) } // Synchronous call args := Request{input, budget} var reply Response err = client.Call("StockDetail.Stocks", &args, &reply) if err != nil { log.Fatal("stock error", err) } fmt.Println(reply.TradeId) fmt.Println(reply.Stocks) fmt.Println(reply.LeftOver) break case 2: fmt.Println("Enter TradeID") var id int fmt.Scanln(&id) fmt.Println(id) client, err := jsonrpc.Dial("tcp", ":1234") if err != nil { log.Fatal("dialing: ", err) } args := RequestCheck{id} var reply ReplyCheck err = client.Call("StockDetail.CheckPortfolio", &args, &reply) if err != nil { log.Fatal("check Error: ", err) } fmt.Println(reply.StocksC) fmt.Println(reply.CurrentMarketValue) fmt.Println(reply.LeftAmount) break default: os.Exit(0) } }
// get DICT3 entries from successor after joining ring func getDict3FromSuccessor() error { if successor.Chordid != chordid { client, err := jsonrpc.Dial(protocol, successor.Address) if err != nil { log.Fatal("dialing:", err) } var reply2 []string req := chordid RpcCall := client.Go("DIC3.RPCGetDict3FromSuccessor", req, &reply2, nil) replyCall := <-RpcCall.Done if replyCall != nil { } client.Close() //iterate through reply2 and insert in my dict3 for _, triplet := range reply2 { arr := strings.Split(triplet, "=") if len(arr) == 3 { key_rel := DKey{arr[0], arr[1]} b := []byte(arr[2]) var f map[string]interface{} err := json.Unmarshal(b, &f) if err != nil { log.Fatal(err) } dict3[key_rel] = f } } fmt.Println("Updated my DICT3, added triplets - ", len(dict3)) } return nil }
// Connect rpc client to rater func testTPitRpcConn(t *testing.T) { var err error tpRPC, err = jsonrpc.Dial("tcp", tpCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal(err) } }
func BenchmarkRpc(b *testing.B) { var d Daemon if err := d.init(); err != nil { b.Fatal(err) } go d.serverloop() defer d.close() if c, err := jsonrpc.Dial("tcp", fmt.Sprintf("127.0.0.1%s", port)); err != nil { b.Error(err) } else { defer c.Close() s := time.Now() for i := 0; i < b.N; i++ { var a content.CompleteAtArgs a.Location.Line = 95 a.Location.Column = 45 a.Location.File.Name = "../net/testdata/CompleteSharp.cs" var cmp1 content.CompletionResult if err := c.Call("Net.CompleteAt", &a, &cmp1); err != nil { b.Error(err) } } e := time.Since(s).Seconds() * 1000 b.Logf("%d calls in %f ms = %f ms/call", b.N, e, e/float64(b.N)) } }
// Connect rpc client to rater func TestFlatstoreitRpcConn(t *testing.T) { var err error flatstoreRpc, err = jsonrpc.Dial("tcp", flatstoreCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal("Could not connect to rater: ", err.Error()) } }
// Connect rpc client to rater func TestPartcsvITRpcConn(t *testing.T) { var err error partcsvRPC, err = jsonrpc.Dial("tcp", partcsvCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal("Could not connect to rater: ", err.Error()) } }
// start a rpc client // if ok , store if func (this *RpcClient) Dial(ip string, port int) (*rpc.Client, error) { client, err := jsonrpc.Dial(RPC_TYPE, ip+":"+strconv.Itoa(port)) if err != nil { log.Println(err) } return client, err }
func callPart1() { var req Request var res Response req.StockSymbolAndPercentage = os.Args[1] req.Budget, _ = strconv.ParseFloat(os.Args[2], 64) client, err := jsonrpc.Dial("tcp", "127.0.0.1:1237") if err != nil { log.Fatal("dialing:", err) } err = client.Call("Obj.Part1", req, &res) if err != nil { log.Fatal("error:", err) } //printing part1 response fmt.Println("\nResponse from server: ") fmt.Println("\nTradeId: ", res.TradeId) fmt.Println("\nStocks: ", res.Stocks) fmt.Println("\nUnvested amount: ", res.UnvestedAmount) }
func rpcClient() *rpc.Client { url, err := url.Parse(settings.RpcServerUrl) if err != nil { log.Fatal(err) } network := url.Scheme if network == "" { network = "unix" } var address string if network == "unix" { address = url.Path } else { address = url.Host } client, err := jsonrpc.Dial(network, address) if err != nil { log.Fatal(err) } return client }
func main() { if len(os.Args) != 2 { fmt.Println("Usage:", os.Args[0], "server") os.Exit(1) } serverAdd := os.Args[1] client, err := jsonrpc.Dial("tcp", serverAdd+":1234") if err != nil { log.Fatal("dialing:", err) } args := Args{17, 8} var reply int err = client.Call("Math.Multiply", args, &reply) if err != nil { log.Fatal("Math error:", err) } fmt.Printf("Math: %d*%d=%d\n", args.A, args.B, reply) var quo Quotient err = client.Call("Math.Divide", args, &quo) if err != nil { log.Fatal("Math error:", err) } fmt.Printf("Math: %d/%d=%d remainder %d\n", args.A, args.B, quo.Quo, quo.Rem) }
func WithRpcServer(f func(c *rpc.Client)) error { file, err := ioutil.TempFile("", "gonit-rpc") if err != nil { return err } path := file.Name() defer os.Remove(path) os.Remove(path) url := "unix://" + path server, err := NewRpcServer(url) if err != nil { return err } go server.Serve() client, err := jsonrpc.Dial("unix", path) if err != nil { return err } defer client.Close() f(client) server.Shutdown() return nil }
func checkPortfolio() { var TradeID int tradeID, _ := strconv.ParseInt(os.Args[1], 10, 32) TradeID = int(tradeID) client, err := jsonrpc.Dial("tcp", "localhost:1234") if err != nil { log.Fatal("dialing:", err) } var pfResponseObj PortfolioResponseObject err = client.Call("StockObject.CheckPortfolio", TradeID, &pfResponseObj) if err != nil { log.Fatal("Wrong Input", err) } fmt.Print("Stocks:") fmt.Println(pfResponseObj.Stocks) fmt.Print("Current Market Value:") fmt.Println(pfResponseObj.CurrentMarketValue) fmt.Print("Unvested Amount:") fmt.Println(pfResponseObj.UnvestedAmount) }
func buyStocks() { var requestObject RequestObject requestObject.StockKey = os.Args[1] budget64, _ := strconv.ParseFloat(os.Args[2], 32) requestObject.Budget = float32(budget64) client, err := jsonrpc.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("dialing:", err) } respObj := new(ResponseObject) err = client.Call("StockObject.ParseRequestObject", requestObject, &respObj) if err != nil { log.Fatal("Error thrown!", err) } fmt.Print("Result:") fmt.Println(respObj.Stocks) fmt.Print("TradeID:") fmt.Println(respObj.TradeID) fmt.Print("UnvestedAmount:") fmt.Println(respObj.UnvestedAmount) }
func callPart2() { // Portfolio var reqPortfolio RequestPortfolio var resPortfolio ResponsePortfolio tradeId, _ := strconv.ParseInt(os.Args[1], 10, 32) reqPortfolio.TradeId = int(tradeId) client, err := jsonrpc.Dial("tcp", "127.0.0.1:1237") if err != nil { log.Fatal("dialing:", err) } err = client.Call("Obj.Part2", reqPortfolio, &resPortfolio) if err != nil { log.Fatal("error:", err) } fmt.Println("Stocks: ", resPortfolio.Stocks) fmt.Println("Current Market value: ", resPortfolio.CurrentMarketValue) fmt.Println("Unvested amount: ", resPortfolio.UnvestedAmount) }
func SendToConsumerExec(consumerList []ConsumerTask, groupId int64) error { channelLimit := make(chan bool, len(consumerList)) successTasks := make(chan int, len(consumerList)) failedTasks := make([]int, 0) queue := make(chan int, 1) log.Printf("Start to send to consumer to execute! consumerList:%s\n", consumerList) for i, v := range consumerList { //TODO Exception Retry go func(consumerTask ConsumerTask, i int) error { defer func() { channelLimit <- true }() log.Printf("Start to send consumer %s, port:%d to execute \n", consumerTask.Address, consumerTask.RpcPort) err := DoCallFunction(consumerTask, queue, i, successTasks) if err != nil { return err } return nil }(v, i) go func() { for v := range queue { failedTasks = append(failedTasks, v) } }() } for i := 0; i < len(consumerList); i++ { <-channelLimit log.Printf("All consumer jobs have done!failedTasks number is %d \n", len(failedTasks)) if len(failedTasks) > 0 { log.Printf("there is failed tasks we need to to retry operation, and select a last time success server! \n") } select { case s := <-successTasks: for _, f := range failedTasks { args := &CommonFunctionCallArgs{ Datas: consumerList[f].Data, GroupId: consumerList[f].GroupId, CallType: "consumer", } client, err := jsonrpc.Dial("tcp", fmt.Sprintf("%s:%d", consumerList[s].Address, consumerList[s].RpcPort)) if err != nil { log.Printf("dial failed!%s \n", consumerList[f]) continue } var result *Status = new(Status) err = client.Call("Call.CallFunction", args, result) if err != nil { log.Printf("dial failed!%s \n", consumerList[f]) continue } } default: log.Printf("Sorry, we don't have success tasks!") break } } return nil }
func TestRpc(t *testing.T) { log4go.Global.Close() log4go.Global.AddFilter("test", log4go.FINEST, &testlogger{t}) var d Daemon if err := d.init(); err != nil { t.Fatal(err) } go d.serverloop() defer d.close() if c, err := jsonrpc.Dial(proto, port); err != nil { t.Error(err) } else { defer c.Close() tests := []struct { skip func() error complete content.Complete rpcname string abs string }{ { func() error { _, e := java.DefaultClasspath() return e }, &java.Java{}, "Java.Complete", "java://type/java/util/jar/JarEntry", }, { func() error { if len(net.DefaultPaths()) == 0 { return fmt.Errorf("net paths are empty...") } return nil }, &net.Net{}, "Net.Complete", "net://type/System.String", }, } for _, test := range tests { if err := test.skip(); err != nil { t.Logf("skipping: %v", err) continue } var a content.CompleteArgs var cmp1, cmp2 content.CompletionResult a.Location.Absolute = test.abs if err := test.complete.Complete(&a, &cmp1); err != nil { t.Error(err) } t.Log("calling", test.rpcname) if err := c.Call(test.rpcname, &a, &cmp2); err != nil { t.Error(err) } else if !reflect.DeepEqual(cmp1, cmp2) { t.Errorf("Results aren't equal: %v\n==============\n:%v", cmp1, cmp2) } } } }
func main() { args := Args{A: 3, B: 10} args.S.A = 1 args.S.B = 2 client, err := jsonrpc.Dial("tcp", URL) if err != nil { log.Fatal("dialing:", err) } { var reply string err = client.Call("sayHello", nil, &reply) if err != nil { log.Fatal("SayHello error:", err) } fmt.Printf("reply: %s\n", reply) } { reply := Replay{} err = client.Call("foo", args, &reply) if err != nil { fmt.Println(err) } fmt.Printf("reply: %v\n", reply) } //client.Close() }
// Connect rpc client to rater func TestTutOsipsCallsRpcConn(t *testing.T) { var err error tutOsipsCallsRpc, err = jsonrpc.Dial("tcp", tutOsipsCallsCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal(err) } }
func (s *RpcSuite) TcpServer(c *C) { host := "localhost:9999" url := "tcp://" + host server, err := NewRpcServer(url) c.Check(err, IsNil) // start the server in a goroutine (Accept blocks) go server.Serve() info.Requests = 0 client, err := jsonrpc.Dial("tcp", host) c.Check(err, IsNil) info := &RpcTest{} err = client.Call("RpcTest.Info", nil, info) c.Check(uint64(1), Equals, info.Requests) c.Check(VERSION, Equals, info.Version) client.Close() // shutdown + cleanup server.Shutdown() }
func main() { flag.Parse() var err error config, err = ReadConfig(configfile) if err != nil { log.Fatal(err) } core := &Core{Visuals: make(map[string]*mrclean.Visual)} go srunService(core) client, err = jsonrpc.Dial(netconn, displayrpc) if err != nil { log.Fatal("dialing:", err) } var ( farg int reply [2]float64 ) err = client.Call("Display.Size", farg, &reply) if err != nil { log.Fatal("Display error:", err) } core.DispW = reply[0] core.DispH = reply[1] log.Printf("core.DispW: %f, core.DispH: %f\n", core.DispW, core.DispH) sigc := make(chan os.Signal, 1) signal.Notify(sigc, syscall.SIGINT) <-sigc }
func main() { flag.Parse() client, err = jsonrpc.Dial(netconn, corerpc) if err != nil { log.Fatal("dialing:", err) } //fmt.Println("Exanmple of message: ", string(buff)) scanner := bufio.NewScanner(os.Stdin) fmt.Print("cmd>") var ret int for scanner.Scan() { fmt.Println("SEND :", scanner.Text()) // Println will add back the final '\n' err := client.Call("Core.Sort", scanner.Text(), &ret) if err != nil { log.Println(err) } if ret == -1 { log.Printf("something wrong in the sorting") } fmt.Print("cmd>") } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } }
func main() { client, err := jsonrpc.Dial("tcp", "localhost:8080") if err != nil { panic(err) } defer client.Close() args := &commons.StockArgs{"GOOG:100%", 2000.0} var reply commons.StockReply for i := 0; i < 1; i++ { err = client.Call("StockService.PurchaseShares", args, &reply) if err != nil { log.Fatal("error:", err) } fmt.Println(reply) } for i := 2; i <= 6; i++ { args := &commons.TransactionArgs{i} var reply commons.TransactionReply err = client.Call("StockService.GetTransactionDetail", args, &reply) if err != nil { log.Fatal("error:", err) } fmt.Println(reply) } }
func TestRpcInvalid(t *testing.T) { var d Daemon if err := d.init(); err != nil { t.Fatal(err) } go d.serverloop() defer d.close() if c, err := jsonrpc.Dial("tcp", fmt.Sprintf("127.0.0.1%s", port)); err != nil { t.Error(err) } else { defer c.Close() tests := []struct { complete content.Complete rpcname string abs string }{ { &java.Java{}, "Java.Complete", "", // Intentional bad request }, } for _, test := range tests { var a content.CompleteArgs var cmp2 content.CompletionResult a.Location.Absolute = test.abs t.Log("calling", test.rpcname) if err := c.Call(test.rpcname, &a, &cmp2); err == nil { t.Error("Expected an error, but didn't receive one") } } } }
func (s *ApiIntSuite) SetUpSuite(c *C) { s.procs = make(map[string]*gonit.Process) s.addProcess("sleepy", []string{"-s", "1h"}) s.addProcess("dopey", []string{"-w", "5s", "-s", "1h"}) s.addProcess("grumpy", []string{"-x", "1", "-s", "1s"}) s.dir = c.MkDir() s.settings = helper.CreateGonitSettings("", s.dir, s.dir) helper.CreateProcessGroupCfg("api_test", s.dir, &gonit.ProcessGroup{Processes: s.procs}) var err error s.gonitCmd, _, err = helper.StartGonit(s.dir) if err != nil { c.Errorf(err.Error()) } s.client, err = jsonrpc.Dial("unix", s.settings.RpcServerUrl) if err != nil { c.Errorf("rpc.Dial: %v", err) } pgs, err := s.statusGroup("api_test") c.Assert(err, IsNil) c.Assert(pgs.Group, HasLen, len(s.procs)) for _, ps := range pgs.Group { c.Assert(ps.Summary.Running, Equals, false) } }
func main() { if len(os.Args) != 2 { fmt.Println("Usage: ", os.Args[0], "server:port") log.Fatal(1) } service := os.Args[1] client, err := jsonrpc.Dial("tcp", service) if err != nil { log.Fatal("dialing:", err) } // Synchronous call args := Args{17, 8} var reply int err = client.Call("Arith.Multiply", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply) var quot Quotient err = client.Call("Arith.Divide", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem) }
// Connect rpc client to rater func TestSMGVoiceApierRpcConn(t *testing.T) { var err error smgRPC, err = jsonrpc.Dial("tcp", daCfg.RPCJSONListen) // We connect over JSON so we can also troubleshoot if needed if err != nil { t.Fatal(err) } }
// Find position on the ring and return successor information. func (t *DIC3) FindPlaceOnRing(request *NodeInfo, reply *NodeInfo) error { if belongsto(request.Chordid, chordid, successor.Chordid) == true { prevSuc := successor reply.Chordid = prevSuc.Chordid reply.Address = prevSuc.Address successor.Chordid = request.Chordid successor.Address = request.Address fingertable[1] = successor fmt.Println("Updated successor as ", successor) return nil } else { np := nearestPredecessor(request.Chordid) client, err := jsonrpc.Dial(protocol, np.Address) if err != nil { log.Fatal("dialing:", err) } var reply2 NodeInfo req2 := NodeInfo{request.Chordid, request.Address} RpcCall := client.Go("DIC3.FindPlaceOnRing", &req2, &reply2, nil) replyCall := <-RpcCall.Done if replyCall != nil { } client.Close() reply.Address = reply2.Address reply.Chordid = reply2.Chordid return nil } return nil }
func buyStocks() { var reqObj StockRequest reqObj.Stocks = os.Args[1] budget64, _ := strconv.ParseFloat(os.Args[2], 32) reqObj.Budget = float32(budget64) client, err := jsonrpc.Dial("tcp", "127.0.0.1:1238") if err != nil { log.Fatal("dialing:", err) } respObj := new(StockResponse) err = client.Call("PortfolioCollection.RequestParser", reqObj, &respObj) if err != nil { log.Fatal("Error: ", err) } fmt.Print("Stocks:") fmt.Println(respObj.Stocks) fmt.Print("TradeID:") fmt.Println(respObj.TradeID) fmt.Print("UnvestedAmount:") fmt.Println(respObj.UnvestedAmount) }