long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

go-rpc

Posted at 2020-06-24 golang 

Http RPC 例子

rpc server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

package main

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

type Args struct {
A,B int
}
type Quotient struct{
Quo, Rem int
}

// rpc 的结构对象
type Arith int
/*
两数相乘函数,被调用
*/
func (t *Arith) Multiply(args *Args, reply *int) error{
*reply = args.A + args.B
return nil
}
/*
两数相除函数,被调用
*/
func (t *Arith) Divide(args *Args, quo *Quotient) error{
if args.B == 0{
return errors.New("Divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
return nil
}

func main() {
arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()

err := http.ListenAndServe(":1234",nil)
if err != nil {
fmt.Println(err.Error())
}
}
rpc client
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
"fmt"
"log"
"net/rpc"
)

type Args struct {
A,B int
}
type Quotient struct {
Quo,Rem int
}

func main() {

client,err := rpc.DialHTTP("tcp","localhost:1234")
if err != nil {
log.Fatal("Dialing: ",err)
return
}
args := Args{17,8}
var reply int
// 远程过程调用
err = client.Call("Arith.Multiply",args,&reply)
if err != nil {
log.Fatal("arith error :",err)
return
}
// 输出回调信息
fmt.Printf("Arith: %d * % d = %d \n",args.A,args.B,reply)
var quot Quotient
err = client.Call("Arith.Divide",args,&quot)
if err != nil {
log.Fatal("arith error :",err)
return
}
fmt.Printf("Arith: %d / %d = %d remainder %d \n",args.A,args.B,quot.Quo,quot.Rem)

}
笔记

使用rpc.Call()函数像调用本地函数一样,至于中间网络请求过程已经被隐藏了。

Share 

 Previous post: go-file Next post: go-redis 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo