/rpcintf/intf.go
package rpcintf
import "net/rpc"
// 代码可以自动生成,通过protoc,插件可以自己写
// Server
// ServerName
const HelloServiceName = "path/to/pkg.HelloService"
// Function list
type HelloServiceInterface = interface {
Hello(request string, reply *string) error
}
// Register Function
func RegisterHelloService(svc HelloServiceInterface) error {
return rpc.RegisterName(HelloServiceName, svc)
}
// Client
type HelloServiceClient struct {
*rpc.Client
}
var _ HelloServiceInterface = (*HelloServiceClient)(nil)
func (p *HelloServiceClient) Hello(request string, reply *string) error {
return p.Client.Call(HelloServiceName+".Hello", request, reply)
}
func DialHelloService(network, address string) (*HelloServiceClient, error) {
c, err := rpc.Dial(network, address)
if nil != err {
return nil, err
}
return &HelloServiceClient{Client: c}, nil
}
server/server.go
package main
import (
"log"
"net"
"net/rpc"
"../rpcintf"
)
type HelloService struct{}
func (p *HelloService) Hello(request string, reply *string) error {
*reply = "hello: " + request
return nil
}
func main() {
rpcintf.RegisterHelloService(new(HelloService))
listener, err := net.Listen("tcp", ":1234")
if nil != err {
log.Fatal("ListenTCP error: ", err)
}
for {
conn, err := listener.Accept()
if nil != err {
log.Fatal("Accept error: ", err)
}
go rpc.ServeConn(conn)
}
}
client/client.go
package main
import (
"fmt"
"log"
"../rpcintf"
)
func main() {
client, err := rpcintf.DialHelloService("tcp", "localhost:1234")
if nil != err {
log.Fatal("dialing: ", err)
}
var reply string
err = client.Hello("Hello", &reply)
if nil != err {
log.Fatal(err)
}
fmt.Println("recv: ", reply)
}