[网络推广玄家配资网]彭迪蒙RPC协议实践入门

RPC(Remote Procedure Call) 是一个计算机通信协议。该协议允许运行与一台计算机的程序调用另一个地址空间的程序,是一个通过发送请求-接受回应进行信息交互的系统。

RPC 的规则

RPC 方法需要为公有,同时有两个可序列化参数,〔 股指期货配资〕,第二个为引用类型(response 调用方接受服务方修改的值)函数返回类型为error。
eg: func Method(request string,response *string)error{
}

Echo demo

server

package main import ( "fmt" "net" "net/rpc" ) type EchoService struct { } func (p *EchoService) Echo(message string, reply *string) error { fmt.Println("client say:", message) *reply = "echo server say :" + message return nil } func main() { fmt.Println("waitting or client..") rpc.RegisterName("EchoService", new(EchoService)) listener, err := net.Listen("tcp", ":8888") if err != nil { panic(err) } conn, err := listener.Accept() if err != nil { panic(err) } rpc.ServeConn(conn) }

client

package main import ( "fmt" "net/rpc" ) func main() { client, err := rpc.Dial("tcp", "localhost:8888") if err != nil { panic(err) } var reply string err = client.Call("EchoService.Echo", "Hello world", &reply) if err != nil { panic(err) } client.Close() fmt.Println(reply) }

结果:

~/.../rpc/server >>> go run ./echo.go waitting or client.. client say: Hello world ~/.../rpc/client >>> go run ./client.go echo server say :Hello world