Skip to main content

rpc 调用代码例子

server端

/**
* Created by GoLand.
* User: 清行
* Contact: 66500852@qq.com
* Date: 2021/6/2
* Time: 20:26
*/
package main

import (
"net"
"net/http"
"net/rpc"
)

type MathUtil struct {
}

type Two struct {
A int
B int
}

func (mu *MathUtil)Asd(req Two,resp *int) error {
*resp = req.A + req.B
return nil
}

func main() {


mathUtil := new(MathUtil)
err := rpc.Register(mathUtil)
if err !=nil {
panic(err.Error())
}

rpc.HandleHTTP()

listen,err := net.Listen("tcp",":8081")
if err !=nil {
panic(err.Error())
}

http.Serve(listen,nil)
}

client 端

/**
* Created by GoLand.
* User: 清行
* Contact: 66500852@qq.com
* Date: 2021/6/2
* Time: 22:14
*/
package main

import (
"com.rpc/ttt"
"fmt"
"net/rpc"
)

func main() {
client,err := rpc.DialHTTP("tcp","localhost:8081")
if err != nil {
panic(err.Error())
}


var c int

//同步方法
err = client.Call("MathUtil.Asd",ttt.Two{A:1,B:555},&c)
if err != nil {
panic(err.Error())
}
fmt.Println(c)

// 异步方法
syncCall := client.Go("MathUtil.Asd",ttt.Two{A:1,B:55},&c,nil)
relayDone := <- syncCall.Done
fmt.Println(relayDone)
fmt.Println(*relayDone)
fmt.Println(c)
}