go标准库的学习-net/rpc/jsonrpc
生活随笔
收集整理的這篇文章主要介紹了
go标准库的学习-net/rpc/jsonrpc
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考: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 mainimport ("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 mainimport ("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.ClientNewClient返回一個新的rpc.Client,以管理對連接另一端的服務的請求。
func?NewClientCodec
func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodecNewClientCodec返回一個在連接上使用JSON-RPC的rpc.ClientCodec。
func?NewServerCodec
func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodecNewServerCodec返回一個在連接上使用JSON-RPC的rpc. ServerCodec。
轉載于:https://www.cnblogs.com/wanghui-garcia/p/10449424.html
總結
以上是生活随笔為你收集整理的go标准库的学习-net/rpc/jsonrpc的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2月28日云栖精选夜读 | 阿里云率先达
- 下一篇: GPS定位系统源码只有这种才是最适合做二