【GO】利用go实现其自带的rpc框架

import (
	"bufio"
	"log"
	"net/rpc"
	"os"
)

type Reply struct {
	Data string
}

func main() {
	client, err := rpc.Dial("tcp", "localhost:12345")
	if err != nil {
		log.Fatal(err)
	}

	in := bufio.NewReader(os.Stdin)
	for {
		line, _, err := in.ReadLine()
		if err != nil {
			log.Fatal(err)
		}
		var reply Reply
		err = client.Call("Listener.GetLine", line, &reply)
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Reply: %v, Data: %v", reply, reply.Data)
	}
}

上述是rpc框架代码的客户端实现,下面是服务端实现:

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

type Listener int

type Reply struct{
	Data string
}

func (l *Listener) GetLine(line []byte, reply *Reply) error {
	rv := string(line)
	fmt.Printf("Receive: %v\n", rv)
	*reply = Reply{rv}
	return nil
}

func main() {
	addy, err := net.ResolveTCPAddr("tcp", "0.0.0.0:12345")
	if err != nil {
		log.Fatal(err)
	}

	inbound, err := net.ListenTCP("tcp", addy)
	if err != nil {
		log.Fatal(err)
	}

	listener := new(Listener)
	rpc.Register(listener)
	rpc.Accept(inbound)
}

  

 不需要下载额外的包,这是go自带的rpc框架。缺点是只能在go语言的程序间互通

posted @ 2020-04-12 12:38  黄烤鸭  阅读(1787)  评论(0编辑  收藏  举报