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() }
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") } }
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) } } }
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) } }
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) } }
func Client() { var err error var c net.Conn c, err = net.DialTimeout("tcp", "127.0.0.1:9999", 1000*1000*1000*30) if err != nil { log.Fatal("dialing:", err) } var client *rpc.Client client = jsonrpc.NewClient(c) // 同步 var a *PlusA = &PlusA{7, 8} var r *PlusR = new(PlusR) ch := make(chan int) for i := 0; i < 10000; i++ { go func() { client.Call("Test.Plus", a, r) <-ch }() } for j := 0; j < 10000; j++ { ch <- 1 fmt.Println(r) } client.Close() c.Close() }
func main() { // establishConnection() client, _ := net.Dial("tcp", "127.0.0.1:1234") c := jsonrpc.NewClient(client) fmt.Println("Welcome to the Yahoo Finance API .What would you like to do ?") for { var option int fmt.Println("SELECT:") fmt.Println("1. Buy the stocks from market.") fmt.Println("2. Check the Portfolio Loss/Gain") fmt.Scan(&option) fmt.Println("=============================================") switch option { /*case '1': os.Exit(0)*/ case 1: optionfirst(client, c) case 2: optionsecond(client, c) default: fmt.Println("You have entered wrong option") } } }
func maino() { var wg sync.WaitGroup wg.Add(1) go startServer() conn, err := net.Dial("tcp", "localhost:8222") if err != nil { panic(err) } defer conn.Close() args := &Args{7, 8} var reply int c := jsonrpc.NewClient(conn) for i := 0; i < 1; i++ { err = c.Call("Arith.Multiply", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply) } wg.Wait() }
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") } }
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 }
func BenchmarkJSONRPC_pipe(b *testing.B) { cli, srv := net.Pipe() go jsonrpc.ServeConn(srv) client := jsonrpc.NewClient(cli) defer client.Close() benchmarkRPC(b, client) }
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") }
func main() { client, err := net.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("dialing:", err) } c := jsonrpc.NewClient(client) // Synchronous call if len(os.Args) != 2 { i, err := strconv.ParseFloat(os.Args[2], 32) if err != nil { log.Fatal("arith error:", err) } args := &Args{os.Args[1], float32(i)} reply := new(Result) err = c.Call("Calculator.Buy", args, reply) if err != nil { log.Fatal("arith error:", err) } fmt.Printf("\n\nTradeId is : %d \n\nStocks: %s \n\nUnvestedAmount :$%.2f\n\n\n ", reply.Id, reply.Status, reply.Balance) } else { id, _ := strconv.Atoi(os.Args[1]) req := &TransId{id} resp := new(Response) err = c.Call("Calculator.Response", req, resp) if err != nil { log.Fatal("Transaction Error :", err) } fmt.Printf("\n\nStocks are : %s \n\nCurrentMarketValue is :$%.2f \n\nUnvestedAmount :$%.2f\n\n ", resp.Stocks, resp.CurrentMarketValue, resp.UnvestedAmount) } }
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() }
// 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 }
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() }
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), } }
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, } }
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() }
func (w *WebServer) start(host string) { http.HandleFunc("/ws-server", func(w http.ResponseWriter, req *http.Request) { s := websocket.Server{ Handler: websocket.Handler(func(ws *websocket.Conn) { jsonrpc.ServeConn(ws) }), } s.ServeHTTP(w, req) log.Println("connected ws-server") }) http.HandleFunc("/ws-client", func(rw http.ResponseWriter, req *http.Request) { s := websocket.Server{ Handler: websocket.Handler(func(ws *websocket.Conn) { w.client = jsonrpc.NewClient(ws) w.ch <- struct{}{} <-w.ch }), } s.ServeHTTP(rw, req) log.Println("connected ws-client") }) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, r.URL.Path[1:]) }) if err := http.ListenAndServe(host, nil); err != nil { log.Fatal(err) } }
func newSubscriberHandler(subscriber string, pipeliningLimit int) (*subscriberHandler, error) { conn, err := net.Dial("tcp", subscriber) if err != nil { return nil, err } client := jsonrpc.NewClient(conn) return &subscriberHandler{client, make(chan struct{}, pipeliningLimit)}, nil }
func DataClient() *rpc.Client { conn, err := net.Dial("unix", "/tmp/data.sock") if err != nil { log.Fatal("dialing:", err) } client := jsonrpc.NewClient(conn) return client }
func NewBackend(backendAddr string) (*rpc.Client, error) { conn, err := secrpc.SecureDial("tcp", backendAddr, []byte(RollbackupCA)) if err != nil { log.Fatal("agent connection: ", err) return nil, err } return jsonrpc.NewClient(conn), nil }
func newMasterHandler(addr string) (*masterHandler, error) { conn, err := net.Dial("tcp", addr) if err != nil { return nil, err } client := jsonrpc.NewClient(conn) return &masterHandler{client}, nil }
func JsonRpcDial(addr string) (*rpc.Client, error) { conn, err := net.Dial("tcp", addr) if err != nil { return nil, errors.NewErr(err) } return jsonrpc.NewClient(conn), nil }
func main() { conn, err := net.Dial("tcp", "localhost:8222") if err != nil { panic(err) } defer conn.Close() u := &gen.User{} u.Init() u.Name = new(string) *u.Name = "Michael Lore" u.Age = new(int32) *u.Age = 47 u.EmailAddress = new(string) *u.EmailAddress = "*****@*****.**" req := &gen.UserServiceAddUserRequest{User: u} req.Init() reply := &gen.UserServiceAddUserResponse{} reply.Init() c := jsonrpc.NewClient(conn) cr := &gen.UserServiceClearRequest{} cr.Init() br := &gen.UserServiceClearResponse{} br.Init() err = c.Call("UserService.Clear", cr, br) if err != nil { fmt.Printf("Clear Error %s\n", err) } for i := 0; i < 10; i++ { t0 := time.Now() err = c.Call("UserService.AddUser", req, reply) t1 := time.Now() fmt.Printf("The call took %v to run.\n", t1.Sub(t0)) if err != nil { fmt.Printf("ERROR %s\n", err) } else { fmt.Printf("Added user %d\n", *reply.Value) } } ar := &gen.UserServiceGetUserRequest{} ar.Id = new(int32) *ar.Id = 1 ars := &gen.UserServiceGetUserResponse{} err = c.Call("UserService.GetUser", ar, ars) if err != nil { fmt.Printf("ERROR %s\n", err) } else { fmt.Printf("Got user %#v\n", ars.Value) } }
func main() { argCount := len(os.Args[1:]) if argCount == 2 { fmt.Println("You have opted to buy stocks (PART 1)") client, err := net.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("dialing:", err) } f, err := strconv.ParseFloat(os.Args[2], 64) if err != nil { log.Fatal("dialing:", err) } args := &Buying_stocks_input{os.Args[1], f} var reply Response_output c := jsonrpc.NewClient(client) err = c.Call("Stocktradingsystem.Buyingstocks", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Println("\n", reply.Message) } else if argCount == 1 { client, err := net.Dial("tcp", "127.0.0.1:1234") fmt.Println("You have opted for portfolio (PART 2)") //fmt.Println("Arguement 1 =" + os.Args[1]) trackid, err := strconv.Atoi(os.Args[1]) var reply Response_output c := jsonrpc.NewClient(client) err = c.Call("Stocktradingsystem.CheckingPortfolio", trackid, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Println("\n", reply.Message) } else { fmt.Println("Incorrect Number of Arguments") fmt.Println("Sample Input for Buyingstocks : go run rpc_client.go YHOO:50%,YHOO:30%,GOOG:10% 10000") } }
func main() { arg := len(os.Args[1:]) if arg == 2 { fmt.Println("buy stocks ") client, err := net.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("dialing:", err) } f, err := strconv.ParseFloat(os.Args[2], 64) if err != nil { log.Fatal("dialing:", err) } args := &buyingStocks{os.Args[1], f} var reply ResponseResult c := jsonrpc.NewClient(client) err = c.Call("Stocktradingsystem.PurchStocks", args, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Println("\n", reply.Message) } else if arg == 1 { client, err := net.Dial("tcp", "127.0.0.1:1234") fmt.Println("second section") //fmt.Println("Arguement 1 =" + os.Args[1]) tradeid1, err := strconv.Atoi(os.Args[1]) var reply ResponseResult c := jsonrpc.NewClient(client) err = c.Call("TradingSystem.CheckingPortfolio", tradeid1, &reply) if err != nil { log.Fatal("arith error:", err) } fmt.Println("\n", reply.Message) } else { fmt.Println("Please check your input") fmt.Println("Syntax to run this system : go run rpc_client.go GOOG:50%,YHOO:30%,GOOG:10% 10000") } }
func main() { var stockinput string var Budget float64 fmt.Printf("Enter stock symbol and Percentage: ") fmt.Scanln(&stockinput) fmt.Printf("Enter the budget ") fmt.Scanln(&Budget) sStocknum := strings.Split(stockinput, ",") count := 0 StockpercentMap := make(map[string]int) for _, v := range sStocknum { sSplited := strings.Split(v, ":") sSplitnumper := strings.Split(sSplited[1], "%") i, err := strconv.Atoi(sSplitnumper[0]) if err != nil { fmt.Println(err) os.Exit(2) } StockpercentMap[sSplited[0]] = i count = count + i } if count != 100 { fmt.Println("Total Percentage not 100") os.Exit(2) } args := &Args{StockpercentMap, Budget} var reply Buyresponse client, err := net.Dial("tcp", "127.0.0.1:1234") if err != nil { log.Fatal("dialing:", err) } c := jsonrpc.NewClient(client) err = c.Call("Stocking.BuyingStocks", args, &reply) if err != nil { log.Fatal("Error While Buying Stocks:", err) } fmt.Println("Trade id: ", reply.TradeID) fmt.Println("stocks: ", reply.Stocksbought) fmt.Println("unvested Amount: ", reply.UnvestedAmount) fmt.Println("") fmt.Printf("Enter the trading id ") fmt.Scanln(&X) var Port PortfolioResponse err = c.Call("Stocking.DisplayingPortfolio", &X, &Port) if err != nil { log.Fatal("Error While DisplayingPortfolio:", err) } fmt.Println("stocks: ", Port.Stocksbought) fmt.Println("current market value: ", Port.CurrentMarketValue) fmt.Println("unvested amount: ", Port.UnvestedAmount) }
func InitMnemosyne(config MnemosyneConfig) { conn, err := net.Dial("tcp", config.Host+":"+config.Port) if err != nil { Logger.Fatal(err) } Mnemosyne = jsonrpc.NewClient(conn) Logger.Info("Connection do Mnemosyne established successfully.") }