日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

go标准库的学习-net/rpc/jsonrpc

發布時間:2024/4/17 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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, &quot) 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。

轉載于:https://www.cnblogs.com/wanghui-garcia/p/10449424.html

總結

以上是生活随笔為你收集整理的go标准库的学习-net/rpc/jsonrpc的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。