go rpc

  server.go

package main

import (
"encoding/json"
"fmt"
"net"
"net/rpc"
"net/rpc/jsonrpc"
)

type RpcTest struct {
}
type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}

func (r *RpcTest) HelloWorld(request map[string]interface{}, resp *string) error {
//fmt.Println(request["name"].(string))
//fmt.Println(request["age"].(int))
//*resp = request["name"].(string) + "您好" + strconv.Itoa(request["age"].(int))
var result Result
result.Code = 200
result.Msg = "ok"
result.Data = request
strResult, err := json.Marshal(result)
if err != nil {
fmt.Println("json错误")
}
*resp = string(strResult)
return nil
}

//主函数
func main() {
err := rpc.RegisterName("hello", new(RpcTest))
if err != nil {
fmt.Println("注册rpc服务失败")
}
listener, err := net.Listen("tcp", "127.0.0.1:8080")
defer listener.Close()
if err != nil {
fmt.Println("创建listener 失败")
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("创建链接失败")
}
fmt.Println("创建链接成功")
go func(conn net.Conn) {
jsonrpc.ServeConn(conn)
conn.Close()
}(conn)
}

}

client.go

package main

import (
"encoding/json"
"fmt"
"net/rpc/jsonrpc"
)

type Result struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]interface{} `json:"data"`
}

func main() {
conn, err := jsonrpc.Dial("tcp", "127.0.0.1:8080")
if err != nil {
fmt.Println(err)
}
var result string
var request = make(map[string]interface{})
request["name"] = "张三"
request["age"] = 10
defer conn.Close()
err = conn.Call("hello.HelloWorld", request, &result)
if err != nil {
fmt.Println(err)
fmt.Println("远程调用失败")
}
var response Result
json.Unmarshal([]byte(result), &response)
fmt.Println(response.Code, response.Msg, response.Data["age"], response.Data["name"])
}



posted on 2022-10-10 21:15  paulversion  阅读(39)  评论(0编辑  收藏  举报