一, 服務器1

package main

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

type RpcServer struct {
}

type RpcRequest struct {
	NumO int
	Num1 int
}
type RpcResponse struct {
	Num int
}

func (s *RpcServer) Add(req RpcRequest, resp *RpcResponse) error { //param0: 請求參數, param1: 返回參數使用*
	resp.Num = req.NumO + req.Num1
	return nil
}

func main() {
	rpc.Register(new(RpcServer))
	rpc.HandleHTTP()
	l, e := net.Listen("tcp", ":9081")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	http.Serve(l, nil)
}

二,服務器2(調用服務器1)

package main

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

type RpcRequest struct {
	NumO int
	Num1 int
}
type RpcResponse struct {
	Num int
}

func main() {
	req := RpcRequest{NumO: 2, Num1: 5}
	var resp RpcResponse = RpcResponse{Num: 0}
	client, err := rpc.DialHTTP("tcp", "localhost:9081")
	if err != nil {
		log.Fatal("dialing:", err)
	}
	//同步處理
	//cerr := client.Call("RpcServer.Add", req, &resp)
	//if cerr != nil {
	//	log.Fatal("call error:", cerr)
	//}
	//fmt.Println(resp)

	//異步處理
	ca := client.Go("RpcServer.Add", &req, &resp, nil)
	for {
		select {
		case <-ca.Done:
			fmt.Println(resp)
			return
		default:
			time.Sleep(time.Second)
			fmt.Println("==")
		}
	}
}

三, 結果

Go之原生RPC (基礎)_Rpc