net/rpc/jsonrpc 不支持http
最后更新于:2022-04-02 02:49:45
[TOC]
## 概述
json-rpc是基于TCP协议实现的 , 目前不支持 http,与 `net/rpc` 类似[net/rpc](net-rpc.md)
```
server.go
rpc.Register(listener)
rpc.Accept(inbound)
改为
rpc.Register(listener)
conn, err := inbound.Accept()
jsonrpc.ServeConn(conn)
```
### 查看发送的json格式
用工具开启 tcp 端口,jsonrpc 尝试链接后打印
` {"method":"Number.Add","params":[{"A":1,"B":2}],"id":0}`
源码中结构体
```
type serverRequest struct {
Method string `json:"method"`
Params *json.RawMessage `json:"params"`
Id *json.RawMessage `json:"id"`
}
type clientRequest struct {
Method string `json:"method"`
Params [1]interface{} `json:"params"`
Id uint64 `json:"id"`
}
```
### 通过第三方工具
```
echo -e '{"method":"Number.Add","params":[{"A":1,"B":2}],"id":0}' | nc 127.0.0.1 12345
```
## demo
server.go
```
type Number int
type Args struct {
A, B int
}
type Reply struct {
C int
}
func (this *Number) Add(args *Args, reply *Reply) error {
fmt.Println(args)
reply.C = args.A + args.B
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(Number)
rpc.Register(listener)
for {
conn, e := inbound.Accept()
if e != nil {
log.Println(e)
}
jsonrpc.ServeConn(conn)
}
}
```
client.go
```
type Args struct {
A, B int
}
type Reply struct {
C int
}
func main() {
client, err := jsonrpc.Dial("tcp", "localhost:12345")
if err != nil {
log.Fatal(err)
}
reply := new(Reply)
err = client.Call("Number.Add", Args{1, 2}, reply)
if err != nil {
log.Println(err)
}
fmt.Println(reply)
}
```
';