同tcprpc, httprpc使用http协议来实现
server端:
package main
import(
"fmt"
"net"
"net/rpc" //rpc包
)
// 定义rpc请求
type AddRequest struct{
Left int
Right int
}
//定义rpc响应
type AddResponse Struct{
Result int
}
type Calc struct{}
// rpc的函数格式:
// 参数1:请求对象(可以是指针/值)
// 参数2:响应对象(可以是指针)
// 返回值:error
func (c *Calc) Add(req AddRequest,resp *AddResponse)error{
fmt.Println("calc.add")
resp.Result=req.Left + req.Right
return nil
}
type AAA struct {}
func(a *AAA)Add(req AddRequest,resp *AddResponse)error{
fmt.Println("add.Add")
return nil
}
func main(){
rpc.Register(&Calc{})
rpc.HandleHTTP() //使用http请求
listener,_:=net.Listen("tcp","8888")
http.Serve(listener)
http.ListenAdnServe("0.0.0.0:8888",nil)
}
client端
type AddRequest struct{
Left int
Right int
}
//定义rpc响应
type AddResponse Struct{
Result int
}
func main(){
client,_:=rpc.DialHTTP("tcp","127.0.0.1:8888")
req:=AddRequest{3,10}
resp:=AddResponse{}
err :=client.Call("Calc.Add",req,&resp)
fmt.println(err,resp)
client.Close()
}
文档更新时间: 2021-09-15 14:33 作者:张尚