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.Register("AAAA",&Calc{}) //类似于别名,可以使用AAAA来调用Calc方法,用于解决结构体名称相同等问题
  34. listener,_:=net.Listen("tcp","0.0.0.0:8888")
  35. for {
  36. conn,err:=listener.Accept()
  37. if err !=nil{
  38. break
  39. }
  40. jsonrpc.Serveconn(conn) //类似http服务端
  41. }
  42. listener.Close()
  43. }

client端

  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. func main(){
  17. client,_:=jsonrpc.Dial("tcp","127.0.0.1:8888")
  18. req:=AddRequest{1,100}
  19. resp:=AddResponse{}
  20. err:=client.Call("Calc.Add",req,&resp) //Call方法会阻塞(同步方式),可以使用Go方法(异步方式)
  21. /*
  22. call :=client.Go("AAAA.Add",req,&resp,nil) //使用异步方式去rpc调用,返回一个结构体,Done为一个管道类型的返回数据,所以下面用select,超时机制。
  23. for {
  24. select {
  25. case result:=<-call.Done:
  26. fmt.Println(result.Reply,result.Error)
  27. default:
  28. fmt.Println(time.Now())
  29. time.Sleep(2 * time.Second)
  30. }
  31. }
  32. */
  33. fmt.Println(err,resp)
  34. }
文档更新时间: 2021-09-15 17:09   作者:张尚