本文整理汇总了Golang中net/rpc.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: InitMsgSvrClient
func InitMsgSvrClient() error {
var err error
MsgSvrClient, err = rpc.Dial(Conf.MsgSvr.Network, Conf.MsgSvr.Addr)
if err != nil {
return err
}
// rpc Ping
go func() {
for {
reply := 0
if err := MsgSvrClient.Call("MessageRPC.Ping", 0, &reply); err != nil {
Log.Error("rpc.Call(\"MessageRPC.Ping\") failed (%v)", err)
rpcTmp, err := rpc.Dial("tcp", Conf.Addr)
if err != nil {
Log.Error("rpc.Dial(\"tcp\", %s) failed (%v)", Conf.Addr, err)
time.Sleep(time.Duration(Conf.MsgSvr.Retry) * time.Second)
Log.Warn("rpc reconnect \"%s\" after %d second", Conf.Addr, Conf.MsgSvr.Retry)
} else {
Log.Info("rpc client reconnect \"%s\" ok", Conf.Addr)
MsgSvrClient = rpcTmp
}
continue
}
// every one second send a heartbeat ping
Log.Debug("rpc ping ok")
time.Sleep(time.Duration(Conf.MsgSvr.Heartbeat) * time.Second)
}
}()
return nil
}
示例2: Call
func (m *mGocode) Call() (interface{}, string) {
e := ""
res := M{}
c, err := rpc.Dial("tcp", mGocodeAddr)
if err != nil {
if serveErr := mGocodeServe(m); serveErr != nil {
return res, "Error starting gocode server: " + serveErr.Error()
}
for i := 0; err != nil && i < 5; i += 1 {
time.Sleep(20 * time.Millisecond)
c, err = rpc.Dial("tcp", mGocodeAddr)
}
if err != nil {
return res, "Error connecting to gocode server: " + err.Error()
}
}
defer c.Close()
switch m.cmd {
case "set":
for k, v := range m.Set {
mGocodeCmdSet(c, k, v)
}
res, e = mGocodeCmdSet(c, "\x00", "\x00")
case "complete":
pos := 0
if m.Complete.Src == "" {
// this is here for testing, the client should always send the src
s, _ := ioutil.ReadFile(m.Complete.Fn)
m.Complete.Src = string(s)
}
for i, _ := range m.Complete.Src {
pos += 1
if pos >= m.Complete.Pos {
pos = i
break
}
}
res, e = mGocodeCmdComplete(c, m.Complete.Fn, []byte(m.Complete.Src), pos)
default:
panic("Unsupported command: gocode: " + m.cmd)
}
return res, e
}
示例3: getTransportOrder
func getTransportOrder(w http.ResponseWriter, r *http.Request) {
u := r.URL
q := u.Query()
in := q.Get("id")
client, err := rpc.Dial("tcp", "localhost:42586")
if err != nil {
log.Fatal(err)
}
var out pack.TransportOrder
err = client.Call("Listener.GetTransportOrderById", in, &out)
if err != nil {
log.Fatal(err)
}
log.Println("web layer - getTransportOrder: ", out)
b, err := json.MarshalIndent(out, "", " ")
if err != nil {
log.Fatal(err)
}
io.WriteString(w, string(b))
}
示例4: TestEcho
func TestEcho(t *testing.T) {
routerAddr := "127.0.0.1:14817"
r, _ := New("id", routerAddr, "")
err := r.Start()
if err != nil {
t.Fatal("router start:", err)
}
defer r.Stop()
time.Sleep(time.Millisecond * 50)
client, err := rpc.Dial("tcp", ":14817")
if err != nil {
t.Fatal("dialing:", err)
}
reply := new(Reply)
err = client.Call("RouterRPC.Echo", "hello router!", reply)
if err != nil {
t.Fatal("router rpc:", err)
}
assert.Equal(t, reply.Value, "hello router!")
}
示例5: getClient
func (lt *localRPCTransport) getClient(id proto.RaftNodeID) (*rpc.Client, error) {
lt.mu.Lock()
defer lt.mu.Unlock()
select {
case <-lt.closed:
return nil, util.Errorf("transport is closed")
default:
}
client, ok := lt.clients[id]
if ok {
return client, nil
}
listener, ok := lt.listeners[id]
if !ok {
return nil, util.Errorf("unknown peer %v", id)
}
address := listener.Addr().String()
// If this wasn't test code we wouldn't want to call Dial while holding the lock.
client, err := rpc.Dial("tcp", address)
if err != nil {
return nil, err
}
lt.clients[id] = client
return client, err
}
示例6: TestRunFailure
func TestRunFailure(t *testing.T) {
// Create a queue & start the resource
q := Queue{authToken: "FailureTest"}
l := startRPCOnce("tcp", addr, &q)
defer l.Close()
// Add the failure tool
tool := new(simpleFailerTooler)
tool.SetUUID(uuid.New())
q.tools = append(q.tools, tool)
// Build the RPC client
client, err := rpc.Dial("tcp", addr)
if err != nil {
t.Fatal("Error dailing RPC servers.", err)
}
// Build the job to send to the simpleFailureTask
params := map[string]string{"failFunc": "Run"}
job := common.NewJob(tool.UUID(), "Failure Test", "GoTestSuite", params)
// Try and create the job... we should get a failure
call := common.RPCCall{Auth: "FailureTest", Job: job}
err = client.Call("Queue.AddTask", call, nil)
if err == nil {
t.Fatal("Failure task's error was not returned.")
}
}
示例7: jujuCMain
// jujuCMain uses JUJU_CONTEXT_ID and JUJU_AGENT_SOCKET to ask a running unit agent
// to execute a Command on our behalf. Individual commands should be exposed
// by symlinking the command name to this executable.
func jujuCMain(commandName string, args []string) (code int, err error) {
code = 1
contextId, err := getenv("JUJU_CONTEXT_ID")
if err != nil {
return
}
dir, err := getwd()
if err != nil {
return
}
req := jujuc.Request{
ContextId: contextId,
Dir: dir,
CommandName: commandName,
Args: args[1:],
}
socketPath, err := getenv("JUJU_AGENT_SOCKET")
if err != nil {
return
}
client, err := rpc.Dial("unix", socketPath)
if err != nil {
return
}
defer client.Close()
var resp jujuc.Response
err = client.Call("Jujuc.Main", req, &resp)
if err != nil {
return
}
os.Stdout.Write(resp.Stdout)
os.Stderr.Write(resp.Stderr)
return resp.Code, nil
}
示例8: TestProvisionerRPC
func TestProvisionerRPC(t *testing.T) {
assert := asserts.NewTestingAsserts(t, true)
// Create the interface to test
p := new(testProvisioner)
// Start the server
server := rpc.NewServer()
RegisterProvisioner(server, p)
address := serveSingleConn(server)
// Create the client over RPC and run some methods to verify it works
client, err := rpc.Dial("tcp", address)
assert.Nil(err, "should be able to connect")
// Test Prepare
config := 42
pClient := Provisioner(client)
pClient.Prepare(config)
assert.True(p.prepareCalled, "prepare should be called")
assert.Equal(p.prepareConfigs, []interface{}{42}, "prepare should be called with right arg")
// Test Provision
ui := &testUi{}
comm := new(packer.MockCommunicator)
pClient.Provision(ui, comm)
assert.True(p.provCalled, "provision should be called")
p.provUi.Say("foo")
assert.True(ui.sayCalled, "say should be called")
}
示例9: main
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: %s server:port\n", os.Args[0])
os.Exit(1)
}
service := os.Args[1]
client, err := rpc.Dial("tcp", service)
if err != nil {
log.Fatal("Dialing:", err)
}
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, ")
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)
}
示例10: ExecClient
func (self *Application) ExecClient() (result bool) {
if flag.NArg() == 0 {
ShowApplicationUsage()
return false
}
rpcClient, err := rpc.Dial(GetServiceSocket(self.tcpPort))
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot open RPC connection: %v\n", err)
return false
}
switch flag.Arg(0) {
case "close":
ClientCloseService(rpcClient)
case "reload":
ClientReloadService(rpcClient)
case "scan":
if flag.NArg() != 2 {
ShowApplicationUsage()
return false
}
inputPath, err := filepath.Abs(flag.Arg(1))
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot get full path from '%s'\n", flag.Arg(1))
return false
}
result := ClientScanEmotions(rpcClient, inputPath)
fmt.Fprintf(os.Stdout, "Text has %d words, %.2f%% positive and %.2f%% negative\n", result.WordCount, result.PercentPositive, result.PercentNegative)
default:
ShowApplicationUsage()
return false
}
return true
}
示例11: GetTradeProfile
func GetTradeProfile() {
var InputFromUser int
InputFromUser = 0
fmt.Println(InputFromUser)
c, err := rpc.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(err)
return
}
if InputFromUser == 2 {
Sr1.TradeId = 1
fmt.Println("Second function here")
err = c.Call("Server.GetTradeProfile", Sr1, &Sresp)
if err != nil {
fmt.Println(err)
}
fmt.Println("Trade ID: ", Sresp.TradeId, " and Remaining amount: ", Sresp.UnvestedAmount)
for index := 0; index < len(Sresp.NumberOfStocks); index++ {
if Sresp.Name[index] != "" {
fmt.Println("Name of Stock", Sresp.Name[index], " Number of Stocks", Sresp.NumberOfStocks[index], " Value of Stock", Sresp.ProfitLoss[index], Sresp.StockValue[index])
}
}
fmt.Println("Current total value ", Sresp.CurrentMarketValue)
}
}
示例12: Test_Proto_Binary_Large_Timeout
func Test_Proto_Binary_Large_Timeout(t *testing.T) {
t.Skip()
srv := &binaryTestServer{&baseTestServer{}}
port, err := srv.listen()
assert.NoError(t, err)
srv.start()
defer srv.Stop()
client, err := rpc.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
assert.NoError(t, err)
defer client.Close()
var res, res1 TestMessage
req := TestMessage{
"12345678910",
[]byte(strings.Repeat("0", 1024*1024)),
}
err = client.Call("ServiceFixture.Ping", &req, &res)
assert.NoError(t, err)
assert.Equal(t, req, res)
time.Sleep(time.Second)
err = client.Call("ServiceFixture.Ping", &req, &res1)
assert.NoError(t, err)
assert.Equal(t, req, res1)
}
示例13: main
func main() {
if len(os.Args) != 2 {
fmt.Println("Usage: ", os.Args[0], "server:port")
os.Exit(1)
}
service := os.Args[1]
client, err := rpc.Dial("tcp", service)
if err != nil {
log.Fatal("dialing:", err)
}
// Synchronous call
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 quot Quotient
err = client.Call("Math.Divide", args, ")
if err != nil {
log.Fatal("Math error:", err)
}
fmt.Printf("Math: %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
}
示例14: Benchmark_Proto_Binary_Large
func Benchmark_Proto_Binary_Large(b *testing.B) {
b.Skip()
srv := &binaryTestServer{&baseTestServer{}}
port, err := srv.listen()
assert.NoError(b, err)
srv.start()
defer srv.Stop()
client, err := rpc.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
assert.NoError(b, err)
defer client.Close()
b.Log(port)
b.ResetTimer()
for i := 0; i < b.N; i++ {
b.StartTimer()
var res TestMessage
req := TestMessage{
"12345678910",
[]byte(strings.Repeat("0", 1024*1024)),
}
err = client.Call("ServiceFixture.Ping", &req, &res)
b.StopTimer()
assert.NoError(b, err)
assert.Equal(b, req, res)
b.SetBytes(int64(len(req.Data) * 2))
}
}
示例15: isLeader
func isLeader(rpc_port int) bool {
client, err := rpc.Dial("tcp", "localhost"+":"+strconv.Itoa(rpc_port))
reply := -1
if err != nil {
return false
} else {
I := 10
errr := client.Call("RaftRPC.Phase", &I, &reply)
if errr != nil {
//fmt.Println("\nError comes")
return false
}
client.Close()
}
//fmt.Printf("\n")
//fmt.Printf("Rk="+strconv.Itoa(reply))
if reply == 1 {
//fmt.Printf("\nReturning true")
return true
}
return false
}