The example in this article describes the two methods of calling RPC Golang. Share to everyone for your reference, specific as follows:
Golang RPC is invoked in two ways, one in the RPC example:
Copy Code code as follows:
Package Main
Import (
"Net/rpc"
"Net/http"
"Log"
"NET"
"Time"
)
Type Args struct {
A, B int
}
Type Arith int
Func (t *arith) Multiply (args *args, reply * ([]string)) Error {
*reply = Append (*reply, "test")
return Nil
}
Func Main () {
Arith: = new (Arith)
Rpc. Register (Arith)
Rpc. Handlehttp ()
L, E: = Net. Listen ("TCP", ": 1234")
If e!= Nil {
Log. Fatal ("Listen error:", e)
}
Go http. Serve (l, Nil)
Time. Sleep (5 * time. Second)
Client, err: = RPC. Dialhttp ("TCP", "127.0.0.1" + ": 1234")
If Err!= nil {
Log. Fatal ("Dialing:", err)
}
Args: = &args{7,8}
Reply: = make ([]string, 10)
Err = client. Call ("Arith.multiply", args, &reply)
If Err!= nil {
Log. Fatal ("Arith error:", err)
}
Log. Println (Reply)
}
The other is using NewServer
This is when RPC has been registered to use another one. That is, a server can only register a type in DEFAULTRPC.
When the server uses Rpc.newserver, the client also needs to make a change
Copy Code code as follows:
Package Main
Import (
"Net/rpc"
"Net/http"
"Log"
"NET"
"Time"
)
Type Args struct {
A, B int
}
Type Arith int
Func (t *arith) Multiply (args *args, reply * ([]string)) Error {
*reply = Append (*reply, "test")
return Nil
}
Func Main () {
NewServer: = RPC. NewServer ()
Newserver.register (New (Arith))
L, E: = Net. Listen ("TCP", "127.0.0.1:1234")//any available address
If e!= Nil {
Log. Fatalf ("net. Listen tcp:0:%v ", E)
}
Go newserver.accept (L)
Newserver.handlehttp ("/foo", "/bar")
Time. Sleep (2 * time. Second)
Address, err: = Net. RESOLVETCPADDR ("TCP", "127.0.0.1:1234")
If Err!= nil {
Panic (ERR)
}
Conn, _: = Net. DIALTCP ("TCP", nil, address)
Defer Conn. Close ()
Client: = RPC. Newclient (conn)
Defer client. Close ()
Args: = &args{7,8}
Reply: = make ([]string, 10)
Err = client. Call ("Arith.multiply", args, &reply)
If Err!= nil {
Log. Fatal ("Arith error:", err)
}
Log. Println (Reply)
}
In the second example
Copy Code code as follows:
Newserver.handlehttp ("/foo", "/bar")
Can be set arbitrarily, the first example is actually set the default two
Here also by the way reply as []slice example to demonstrate the next
I hope this article will help you with your go language program.