Go语言学习之TCP 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
49
50
51
52
53
54
55
56
57
58
59
60
1package main
2
3import (
4    "errors"
5    "fmt"
6    "net"
7    "net/rpc"
8    "os"
9)
10
11type Args struct {
12    A, B int
13}
14
15type Quotient struct {
16    Quo, Rem int
17}
18
19type Arith int
20
21func (t *Arith) Multiply(args *Args, reply *int) error {
22    *reply = args.A * args.B
23    return nil
24}
25
26func (t *Arith) Divide(args *Args, quo *Quotient) error {
27    if args.B == 0 {
28        return errors.New("divede by zero")
29    }
30    quo.Quo = args.A / args.B
31    quo.Rem = args.A % args.B
32    return nil
33}
34
35func main() {
36    arith := new(Arith)
37    rpc.Register(arith)
38
39    tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")
40    if err != nil {
41        fmt.Println("Fatal error:", err)
42        os.Exit(1)
43    }
44
45    listener, err := net.ListenTCP("tcp", tcpAddr)
46    if err != nil {
47        fmt.Println("Fatal error:", err)
48        os.Exit(1)
49    }
50
51    for {
52        conn, err := listener.Accept()
53        if err != nil {
54            continue
55        }
56        rpc.ServeConn(conn)
57    }
58}
59
60

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
1package main
2
3import (
4    "fmt"
5    "log"
6    "net/rpc"
7)
8
9type Args struct {
10    A, B int
11}
12
13type Quotient struct {
14    Quo, Rem int
15}
16
17func main() {
18    service := "127.0.0.1:1234"
19
20    client, err := rpc.Dial("tcp", service)
21    if err != nil {
22        log.Fatal("dialing:", err)
23    }
24
25    args := Args{17, 8}
26    var reply int
27    err = client.Call("Arith.Multiply", args, &reply)
28    if err != nil {
29        log.Fatal("arith error :", err)
30    }
31    fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
32
33    var quot Quotient
34    err = client.Call("Arith.Divide", args, &quot)
35    if err != nil {
36        log.Fatal("arith error:", err)
37    }
38    fmt.Printf("Arith : %d/%d=%d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem)
39}
40
41

rpc原理

http://blog.csdn.net/libinbin_1014/article/details/73302757

给TA打赏
共{{data.count}}人
人已打赏
安全经验

人们为何痛恨Google Adsense

2021-10-11 16:36:11

安全经验

安全咨询服务

2022-1-12 14:11:49

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索