//抄襲一遍,練手
/**
golang net/rpc http
*/
package main
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"net/rpc"
"time"
)
var p = fmt.Println
type Args struct {
A, B int
}
type Quotient struct {
Quo, Rem int
}
type Arith int
func (this *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
func (this *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() {
//server
arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP() //DefaultRPCPath
l, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
go http.Serve(l, nil)
time.Sleep(2 * time.Second)
//client
// Synchronous call
client, err := rpc.DialHTTP("tcp", "127.0.0.1:1234")
if err != nil {
log.Fatal("dialing:", err)
}
args := &Args{7, 8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d\n", args.A, args.B, reply)
// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done // will be equal to divCall
// check errors, print, etc.
//7除8 商0 餘7
p(replyCall.Reply)
time.Sleep(1 * time.Hour)
//http://127.0.0.1:1234/debug/rpc
}