Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第五章 网络编程 RPC编程部分代码没有 #18

Open
kingofzihua opened this issue Aug 10, 2020 · 1 comment
Open

第五章 网络编程 RPC编程部分代码没有 #18

kingofzihua opened this issue Aug 10, 2020 · 1 comment

Comments

@kingofzihua
Copy link

5.3.1 小结 rpcserver.go 代码没有

@yinjilong
Copy link

//rpc-serv.go
package main

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

type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

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() {
	fmt.Println("start RPC server")

	arith := new(Arith)
	rpc.Register(arith)
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen erros:", e)
	}

	go http.Serve(l, nil)

	//to avoid terminate main thread during goroutine
	time.Sleep(1000 * time.Second)

}

//rpc-client.go
package main

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

type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

func main() {
	fmt.Println("RPC test client")
	client, err := rpc.DialHTTP("tcp", "127.0.0.1:1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}

	args := &Args{13, 8}
	var reply int
	err = client.Call("Arith.Multiply", args, &reply)
	if err != nil {
		log.Fatal("arigh error:", err)
	}
	fmt.Printf("Arith:%d*%d=%d\n", args.A, args.B, reply)

	//try async call
	quotient := new(Quotient)
	divCall := client.Go("Arith.Divide", args, &quotient, nil)
	<-divCall.Done
	fmt.Printf("Arith:%d / %d = %d ...%d\n", args.A, args.B, quotient.Quo, quotient.Rem)

	client.Close()

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants