[GO] Use go to implement its own rpc framework

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)
	}
}

The above is the client implementation of the rpc framework code, and the following is the server implementation:

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)
}

  

 No need to download additional packages, this is the rpc framework that comes with go. The disadvantage is that it can only communicate between programs in go language

Guess you like

Origin www.cnblogs.com/sbhyc/p/12684669.html