同tcprpc, httprpc使用http协议来实现

server端:

  1. package main
  2. import(
  3. "fmt"
  4. "net"
  5. "net/rpc" //rpc包
  6. )
  7. // 定义rpc请求
  8. type AddRequest struct{
  9. Left int
  10. Right int
  11. }
  12. //定义rpc响应
  13. type AddResponse Struct{
  14. Result int
  15. }
  16. type Calc struct{}
  17. // rpc的函数格式:
  18. // 参数1:请求对象(可以是指针/值)
  19. // 参数2:响应对象(可以是指针)
  20. // 返回值:error
  21. func (c *Calc) Add(req AddRequest,resp *AddResponse)error{
  22. fmt.Println("calc.add")
  23. resp.Result=req.Left + req.Right
  24. return nil
  25. }
  26. type AAA struct {}
  27. func(a *AAA)Add(req AddRequest,resp *AddResponse)error{
  28. fmt.Println("add.Add")
  29. return nil
  30. }
  31. func main(){
  32. rpc.Register(&Calc{})
  33. rpc.HandleHTTP() //使用http请求
  34. listener,_:=net.Listen("tcp","8888")
  35. http.Serve(listener)
  36. http.ListenAdnServe("0.0.0.0:8888",nil)
  37. }

client端

  1. type AddRequest struct{
  2. Left int
  3. Right int
  4. }
  5. //定义rpc响应
  6. type AddResponse Struct{
  7. Result int
  8. }
  9. func main(){
  10. client,_:=rpc.DialHTTP("tcp","127.0.0.1:8888")
  11. req:=AddRequest{3,10}
  12. resp:=AddResponse{}
  13. err :=client.Call("Calc.Add",req,&resp)
  14. fmt.println(err,resp)
  15. client.Close()
  16. }
文档更新时间: 2021-09-15 14:33   作者:张尚