服务端
package main
import (
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"sync"
)
type Params struct {
Width, Height int
}
type Rect struct{}
func (r *Rect) Area(p Params, ret *int) error {
*ret = p.Width * p.Height
return nil
}
func main() {
rect := new(Rect)
//注册一个rect服务
rpc.Register(rect)
var wg sync.WaitGroup
wg.Add(1)
go func() {
tcpaddr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:8082")
tcplisten, err := net.ListenTCP("tcp", tcpaddr)
if err != nil {
log.Fatal(err)
defer wg.Done()
}
for {
conn, err := tcplisten.Accept()
if err != nil {
continue
}
go jsonrpc.ServeConn(conn)
}
}()
log.Println("tcp json-rpc service start success addr:8082")
wg.Wait()
}
客户端
package main
import (
"fmt"
"log"
"net/rpc/jsonrpc"
)
type Params struct {
Width, Height int
}
func main() {
//连接远程rpc服务
rpc, err := jsonrpc.Dial("tcp", "127.0.0.1:8082")
if err != nil {
log.Fatal(err)
}
//调用远程方法
ret := 0
if err := rpc.Call("Rect.Area", Params{150, 100}, &ret); err != nil {
log.Fatal(err)
}
fmt.Println(ret)
}
启动
go run server.go #服务端
go run client.go #客户端
网友评论