golang中rpc

package http_rpc

import (
	"log"
)

type Arith int

type Args struct {
	A, B int
}

func (t *Arith) Multiply(args Args, result *int) error {
	log.Printf("Multiply %d with %d\n", args.A, args.B)
	*result = args.A * args.B
	return nil
}

首先定义结构体,然后在结构体中给结构体绑定相应的方法,该方法有传参和返回值。

package main

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

func main() {
	arith := new(http_rpc.Arith)
	rpc.Register(arith)
	rpc.HandleHTTP()
	if err := http.ListenAndServe(":1234", nil);err!=nil{
		log.Fatal("error server...")
	}
}

rpc的服务端,创建结构体对象,并将该对象进行注册,启动handleHTTP,启动相应的端口。

func main() {
	client, e := rpc.DialHTTP("tcp", ":1234")
	if e!=nil {
		fmt.Errorf("e ",e)
	}
	args := http_rpc.Args{A: 2, B: 3}
	var reply int
	client.Call("Arith.Multiply",args,&reply)
	fmt.Println(reply)
}

rpc客户端,使用rpc.DialHTTP,然后用得到的对象调用方法,传入参数需要注意:结构体名.方法名,传入参数,返回值。
然后结果就放入返回值中了。

猜你喜欢

转载自blog.csdn.net/qq_30505673/article/details/89704883
今日推荐