47
loading...
This website collects cookies to deliver better user experience
net/rpc
and net/jsonrpc
.client
and server
. rpc-banner-demo
├── client
│ └── main.go
└── server
└── main.go
package main
import (
"log"
"net"
"net/http"
"net/rpc"
)
// an RPC server in Go
type Args struct{}
type BannerMessageServer string
func (t *BannerMessageServer) GetBannerMessage(args *Args, reply *string) error {
*reply = "This is a message from the RPC server"
return nil
}
func main() {
// create and register the rpc
banner := new(BannerMessageServer)
rpc.Register(banner)
rpc.HandleHTTP()
// set a port for the server
port := ":1122"
// listen for requests on 1122
listener, err := net.Listen("tcp", port)
if err != nil {
log.Fatal("listen error: ", err)
}
http.Serve(listener, nil)
}
GetBannerMessage
of the BannerMessageServer
type.package main
import (
"log"
"net/rpc"
)
// rpc client
type Args struct{}
func main() {
hostname := "localhost"
port := ":1122"
var reply string
args := Args{}
client, err := rpc.DialHTTP("tcp", hostname+port)
if err != nil {
log.Fatal("dialing: ", err)
}
// Call normally takes service name.function name, args and
// the address of the variable that hold the reply. Here we
// have no args in the demo therefore we can pass the empty
// args struct.
err = client.Call("BannerMessageServer.GetBannerMessage", args, &reply)
if err != nil {
log.Fatal("error", err)
}
// log the result
log.Printf("%s\n", reply)
}
localhost
and :1122
in our demo case. service.function
and the reply will be assigned to the address of of our local variable reply
.go run server/main.go
, in the other run go run client/main.go
and marvel at your results