package main
import (
"log"
"net"
"net/rpc"
)
type HelloService struct { //空结构体
}
func (p *HelloService) Hello(request string, reply *string) error { //为hello结构体绑定hello方法
*reply = "你好:" + request //拼接字符串
return nil //返回空值
}
func main() {
rpc.RegisterName("HelloService", new(HelloService))
listener, err := net.Listen("tcp", "localhost:1234")
if err != nil {
log.Fatal("ListenTCP erro :", err)
}
conn, err := listener.Accept()
if err != nil {
log.Fatal("Accept error:", err)
}
rpc.ServeConn(conn)
}
package main
import (
"fmt"
"log"
"net/rpc"
)
func main() {
client, err := rpc.Dial("tcp", "localhost:1234")
if err != nil {
log.Fatal("dialing : ", err)
}
var reply string
err = client.Call("HelloService.Hello", "hello", &reply)
if err != nil {
log.Fatal(err)
}
fmt.Println(reply)
}
返回结果
你好:hello