在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
import ( "bufio" "log" "net/rpc" "os" ) type Reply struct { Data string } func main() { client, err := rpc.Dial("tcp", "localhost:12345") if err != nil { log.Fatal(err) } in := bufio.NewReader(os.Stdin) for { line, _, err := in.ReadLine() if err != nil { log.Fatal(err) } var reply Reply err = client.Call("Listener.GetLine", line, &reply) if err != nil { log.Fatal(err) } log.Printf("Reply: %v, Data: %v", reply, reply.Data) } } 上述是rpc框架代码的客户端实现,下面是服务端实现: import ( "fmt" "log" "net" "net/rpc" ) type Listener int type Reply struct{ Data string } func (l *Listener) GetLine(line []byte, reply *Reply) error { rv := string(line) fmt.Printf("Receive: %v\n", rv) *reply = Reply{rv} return nil } func main() { addy, err := net.ResolveTCPAddr("tcp", "0.0.0.0:12345") if err != nil { log.Fatal(err) } inbound, err := net.ListenTCP("tcp", addy) if err != nil { log.Fatal(err) } listener := new(Listener) rpc.Register(listener) rpc.Accept(inbound) }
不需要下载额外的包,这是go自带的rpc框架。缺点是只能在go语言的程序间互通 |
请发表评论