package public

type Args struct {
    A, B int
}

type Quotient struct {
    Quo, Rem int
}

  

server.go

package main

import (
	"Songzhibin/test/rpc/public"
	"errors"
	"fmt"
	"net"
	"net/rpc"
)

type Arith int

func (t *Arith) Multiply(args *public.Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}

func (t *Arith) Divide(args *public.Args, quo *public.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() 不使用 HandleHTTP()
	l, err := net.Listen("tcp", ":1234")
	if err != nil {
		fmt.Println(err)
		return
	}
	for {
		// 获取连接
		conn, err := l.Accept()
		if err != nil {
			fmt.Println(err)
			return
		}
		rpc.ServeConn(conn)
	}
	select {}
}

  

  

client.go

package main

import (
	"Songzhibin/test/rpc/public"
	"fmt"
	"log"
	"net/rpc"
)

func main() {
	// 这里只需要将 DialHTTP改为Dial 即可
	client, err := rpc.Dial("tcp", "127.0.0.1:1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}
	// 然后,客户端可以执行远程调用:

	// Synchronous call
	args := &public.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(public.Quotient)
	divCall := client.Go("Arith.Divide", args, quotient, nil)
	replyCall := <-divCall.Done // will be equal to divCall
	// check errors, print, etc.
	fmt.Printf("%#v\n", replyCall)
}

  

  

 

 

Json-RPC(TCP)

public.go  

package public

type Args struct {
    A, B int
}

type Quotient struct {
    Quo, Rem int
}