server.go
package main
import (
"log"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
)
type Args struct {
A int
B int
}
type Number struct{}
// 方法参数列表必须为此格式
func (num *Number) Sum(args *Args, sum *int) error {
*sum = args.A + args.B
return nil
}
func TcpServer() {
ln, err := net.Listen("tcp", "127.0.0.1:9008")
if err != nil {
log.Fatalln("net.Listen error:", err)
}
log.Println("start connection")
for {
// 接收客户端连接请求
conn, err := ln.Accept()
if err != nil {
log.Println("ln.Accept error:", err)
continue
}
// 处理客户端请求
go func(conn net.Conn) {
log.Println("new client in coming")
jsonrpc.ServeConn(conn)
}(conn)
}
}
func HttpServer() {
rpc.HandleHTTP()
ln, err := net.Listen("tcp", "127.0.0.1:9009")
if err != nil {
log.Fatalln("net.Listen error:", err)
}
err = http.Serve(ln, nil)
if err != nil {
log.Fatalln("http.Serve error:", err)
}
}
func main() {
err := rpc.Register(&Number{})
if err != nil {
log.Fatalln("rpc.Register error:", err)
}
go TcpServer()
go HttpServer()
select {}
}
client.go
package main
import (
"log"
"net/rpc"
"net/rpc/jsonrpc"
"time"
)
type Args struct {
A int
B int
}
func Tcp() {
client, err := jsonrpc.Dial("tcp", "127.0.0.1:9008")
if err != nil {
log.Fatalln("jsonrpc.Dial error:", err)
}
args := &Args{9, 2}
var sum int
// 调用方法
err = client.Call("Number.Sum", args, &sum)
if err != nil {
log.Fatalln("conn.Call error:", err)
}
log.Println("Tcp result:", sum)
}
func Http() {
client, err := rpc.DialHTTP("tcp", "127.0.0.1:9009")
if err != nil {
log.Fatalln("jsonrpc.Dial error:", err)
}
args := &Args{9, 2}
var sum int
// 调用方法
err = client.Call("Number.Sum", args, &sum)
if err != nil {
log.Fatalln("conn.Call error:", err)
}
log.Println("Http result:", sum)
}
func Async() {
client, err := jsonrpc.Dial("tcp", "127.0.0.1:9008")
// client, err := rpc.DialHTTP("tcp", "127.0.0.1:9009")
if err != nil {
log.Fatalln("jsonrpc.Dial error:", err)
}
args := &Args{9, 2}
var sum int
call := client.Go("Number.Sum", args, &sum, nil)
<-call.Done
log.Println("Async result:", sum)
}
func main() {
go Tcp()
go Http()
go Async()
<-time.After(time.Second)
}
来源:oschina
链接:https://my.oschina.net/lanseyujie/blog/4319657