This is a creation in Article, where the information may have evolved or changed.
RPC Remote Procedure call.
The Go language support for RPC has the following requirements:
1. Registering RPC as an object
The 2.RPC function must be the public function of the object. Public, which is the first letter capitalized function
The 3.RPC function must have 2 parameters, a public type, or a go inline type.
The 2nd parameter of the 4.RPC function is the return value and must be a pointer type.
The 5.RPC function must return a value of type error.
Func (this *t) MethodName (args t1,reply *t2) error
By default, the GOB is encoded and decoded by the line data.
TCP connections
/** * Created by Administrator on 13-12-31. */package mainimport ("Errors" "NET/RPC" "Net" "FMT" "OS") type Args struct {I, J int}type MyMethod intfunc (this *mymethod) M Ult (args *args, reply *int) error {if args = = Nil | | reply = nil {return errors. New ("Nil paramters!")} *reply = args. I*args. Jreturn nil}type divresult struct {Quo, Rem int}func (this *mymethod) Div (args *args, reply *divresult) error{if args = n Il | | Reply = = Nil {return errors. New ("Nil paramters!")} If args. J = = 0 {return errors. New ("/0!")} Reply. Quo = args. I/args. Jreply.rem = args. I% args. Jreturn Nil}func Main () {mm: = new (MyMethod) server: = RPC. NewServer () server. Register (mm) listener, err: = Net. Listen ("TCP", ": 7777") defer listener. Close () if err! = Nil {fmt. fprintf (OS. Stderr, "Error%s\n", err. Error ()) Return}server. Accept (Listener)}
/** * Created by Administrator on 13-12-31. */package mainimport ("Net/rpc" "FMT" "OS") type args struct {I, J int}type MyMethod int//func (this *mymethod) Mult (args *a RGS, reply *int) error {//if args = Nil | | reply = nil {//return errors. New ("Nil paramters!") }//*reply = args. I*args. J//return nil//}type divresult struct {Quo, Rem int}//func (this *mymethod) Div (args *args, reply *divresult) {//reply. Quo = args. I/args. J//reply. Rem = args. J% args. J//}func Main () {pclient, err: = RPC. Dial ("TCP", "127.0.0.1:7777") if err! = Nil {fmt. fprintf (OS. Stderr, "ERR:%s\n", err. Error ()) return}defer pclient.close ()Sync rpcvar Multresult interr = Pclient.call ("Mymethod.mult", &args{2, 7}, &multresult) if err! = Nil {fmt. fprintf (OS. Stderr, "ERR:%s\n", err. Error ()) return}fmt. fprintf (OS. Stdout, "Multresult =%d\n", Multresult)//Async Rpcvar divresult Divresultpcall: = Pclient.go ("Mymethod.div", &Args{5, 2 }, &divresult, nil) if pcall! = nil {fmt. fprintf (OS. Stderr, "Pcall:%v%v\n", Pcall, pcall.reply) if replycall, OK: = <-pCall.Done; OK {fmt. fprintf (OS. Stderr, "Replycall:%v%v\n", Replycall, Replycall.reply)}}