1.参考资料

https://gist.github.com/nicerobot/8954764

2.目录和源码

2.1 主目录是go-jsonrpc-thin,子目录和源码文件是

.
├── client
│   └── main.go
├── server
│   ├── main.go
└── shared

    └── SharedStructures.go

2.2 SharedStructures.go

package shared

type Args struct {
	X, Y int
}

type Reply struct {
	S int
	Q string
}

type Arith struct{}

func (t *Arith) Add(args *Args, reply *Reply) error {
	reply.S = args.X + args.Y
	reply.Q = "test demo"
	return nil
}

2.3 server/main.go

package main

import (
	"log"
	"net"
	"net/rpc"
	"net/rpc/jsonrpc"

	"path/to/go-jsonrpc-thin/shared"
)

func main() {

	arith := new(shared.Arith)
	server := rpc.NewServer()
	server.Register(arith)
	server.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
	listener, e := net.Listen("tcp", ":1234")
	if e != nil {
		log.Fatal("listen error:", e)
	}
	for {
		if conn, err := listener.Accept(); err != nil {
			log.Fatal("accept error: " + err.Error())
		} else {
			log.Printf("new connection established\n")
			go server.ServeCodec(jsonrpc.NewServerCodec(conn))
		}
	}

}

2.4 client/main.go

package main

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

	"path/to/go-jsonrpc-thin/shared"
)

func main() {

	client, err := net.Dial("tcp", "127.0.0.1:1234")
	if err != nil {
		log.Fatal("dialing:", err)
	}
	// Synchronous call
	args := &shared.Args{7, 8}
	var reply shared.Reply
	c := jsonrpc.NewClient(client)
	err = c.Call("Arith.Add", args, &reply)
	if err != nil {
		log.Fatal("arith error:", err)
	}
	fmt.Printf("Result: %d+%d=%d\n", args.X, args.Y, reply.S)
	fmt.Println(reply)
}

3.运行

3.1 运行./server/server

3.2 运行./client/client

即可看到结果

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐