參考:https://studygolang.com/pkgdoc
導入方式:
import "net/rpc/jsonrpc"
jsonrpc包實現了JSON-RPC的ClientCodec和ServerCodec接口,可用於rpc包。
func Dial
func Dial(network, address string) (*rpc.Client, error)
Dial在指定的網絡和地址連接一個JSON-RPC服務端
func ServeConn
func ServeConn(conn io.ReadWriteCloser)
ServeConn在單個連接上執行DefaultServer。ServeConn會阻塞,服務該連接直到客戶端掛起。調用者一般應另開線程調用本函數:"go serveConn(conn)"。ServeConn在該連接使用JSON編解碼格式。
舉例:
JSON RPC
服務端:
package main
import (
"fmt" "net" "net/rpc" "net/rpc/jsonrpc" "errors" "os" ) type Args struct{ A, B int } type Quotient struct{ Quo, Rem int } type Arith int func (t *Arith) Multiply(args *Args, reply *int) error{ *reply = args.A * args.B return nil } func (t *Arith) Divide(args *Args, quo *Quotient) error{ if args.B == 0{ return errors.New("divide by zero") } quo.Quo = args.A / args.B quo.Rem = args.A % args.B return nil } func main() { arith := new(Arith) rpc.Register(arith) tcpAddr, err := net.ResolveTCPAddr("tcp", ":1234")//jsonrpc是基於TCP協議的,現在他還不支持http協議 if err != nil{ fmt.Println(err.Error()) os.Exit(1) } listener, err := net.ListenTCP("tcp", tcpAddr) if err != nil{ fmt.Println(err.Error()) os.Exit(1) } for{ conn, err := listener.Accept() if err != nil{ continue } jsonrpc.ServeConn(conn) } }
客戶端:
package main
import (
"fmt" "net/rpc/jsonrpc" "log" "os" ) type Args struct{ A, B int } type Quotient struct{ Quo, Rem int } func main() { if len(os.Args) != 2{ fmt.Println("Usage: ", os.Args[0], "server:port") os.Exit(1) } service := os.Args[1] client, err := jsonrpc.Dial("tcp", service) if err != nil{ log.Fatal("dialing : ", err) } //Synchronous call args := Args{17, 8} var reply int err = client.Call("Arith.Multiply", args, &reply) if err != nil{ log.Fatal("arith error : ", err) } fmt.Printf("Arith: %d*%d = %d \n", args.A, args.B, reply) var quot Quotient err = client.Call("Arith.Divide", args, ") if err != nil{ log.Fatal("arith error : ", err) } fmt.Printf("Arith: %d/%d = %d remainder %d\n", args.A, args.B, quot.Quo, quot.Rem) }
客戶端返回:
userdeMBP:go-learning user$ go run test.go 127.0.0.1:1234 Arith: 17*8 = 136 Arith: 17/8 = 2 remainder 1
func NewClient
func NewClient(conn io.ReadWriteCloser) *rpc.Client
NewClient返回一個新的rpc.Client,以管理對連接另一端的服務的請求。
func NewClientCodec
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec
NewClientCodec返回一個在連接上使用JSON-RPC的rpc.ClientCodec。
func NewServerCodec
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec
NewServerCodec返回一個在連接上使用JSON-RPC的rpc. ServerCodec。