go 简单的RPC服务与客户端通讯
// 服务器代码
package main
// rpc 服务
import (
"net/rpc"
"net"
"log"
"net/http"
)
type Name struct {
MyName string
}
type Age struct {
MyAge string
}
type My struct {
Name string
Age string
}
// 暴露api 接收一个Name指针结构 和一个指针字符串 返回一个错误信息
func (m *My) SetName (name *Name,s *string) error{
*s = name.MyName+"Set-Name"
return nil
}
// 暴露api
func (m *My) SetAge (age *Age,s *string) error{
*s = age.MyAge
return nil
}
func main() {
arith:= new(My)
rpc.Register(arith) // 注册
rpc.HandleHTTP() // 初始化
l,e:=net.Listen("tcp",":8080")
if e!=nil {
log.Fatal("sevice error.")
}
// 启动服务
http.Serve(l,nil)
}
客户端代码
package main
// rpc 客户端
import (
"net/rpc"
"log"
"fmt"
)
type MName struct {
MyName string
}
func main() {
// 拨号链接服务
client,err:=rpc.DialHTTP("tcp","127.0.0.1:8080")
if err!=nil {
log.Fatal("client not find")
}
name:=&MName{"lyl"} // 创建服务需要的结构参数
var g string // 接收数据返回的类型
err = client.Call("My.SetName",name,&g)
fmt.Println(g) // 输出返回值
} // 服务器代码 package main // rpc 服务 import ( "net/rpc" "net" "log" "net/http" ) type Name struct { MyName string } type Age struct { MyAge string } type My struct { Name string Age string } // 暴露api 接收一个Name指针结构 和一个指针字符串 返回一个错误信息 func (m *My) SetName (name *Name,s *string) error{ *s = name.MyName+"Set-Name" return nil } // 暴露api func (m *My) SetAge (age *Age,s *string) error{ *s = age.MyAge return nil } func main() { arith:= new(My) rpc.Register(arith) // 注册 rpc.HandleHTTP() // 初始化 l,e:=net.Listen("tcp",":8080") if e!=nil { log.Fatal("sevice error.") } // 启动服务 http.Serve(l,nil) } 客户端代码 package main // rpc 客户端 import ( "net/rpc" "log" "fmt" ) type MName struct { MyName string } func main() { // 拨号链接服务 client,err:=rpc.DialHTTP("tcp","127.0.0.1:8080") if err!=nil { log.Fatal("client not find") } name:=&MName{"lyl"} // 创建服务需要的结构参数 var g string // 接收数据返回的类型 err = client.Call("My.SetName",name,&g) fmt.Println(g) // 输出返回值 }
上一篇:
Java架构师技术进阶路线图
