json on tcp
This commit is contained in:
parent
45ef1f021e
commit
8fb74b563e
@ -1,5 +1,7 @@
|
||||
# RPC
|
||||
|
||||
[课件](https://gitee.com/infraboard/go-course/blob/master/day15/rpc.md#json-on-http)
|
||||
|
||||
+ Go语言内置RPC框架的使用(原始)
|
||||
+ 基于接口封装优化好的RPC
|
||||
+ Protobuf介绍与环境准备
|
||||
@ -33,5 +35,6 @@ Protobuf的包机制以及使用方式
|
||||
|
||||
RPC是远程过程调用的简称,是分布式系统中不同节点间流行的通信方式。在互联网时代,RPC已经和IPC一样成为一个不可或缺的基础构件。
|
||||
|
||||
## GO语言内置RPC
|
||||
|
||||
```sh
|
||||
echo -e '{"method":"HelloService.Hello","params":[{"my_name":"bob"}],"id":1}' | nc localhost 1234
|
||||
```
|
||||
|
@ -3,6 +3,7 @@ package main
|
||||
import (
|
||||
"net"
|
||||
"net/rpc"
|
||||
"net/rpc/jsonrpc"
|
||||
|
||||
"gitlab.com/go-course-project/go17/skills/rpc/hello_world/service"
|
||||
)
|
||||
@ -45,6 +46,10 @@ func main() {
|
||||
continue
|
||||
}
|
||||
// 用户的net层数据 转交给 rpc框架
|
||||
go rpc.ServeConn(conn)
|
||||
// go rpc.ServeConn(conn)
|
||||
// json codec(server)
|
||||
// req(bytes) --> obj
|
||||
// resp(obj) --> bytes
|
||||
go rpc.ServeCodec(jsonrpc.NewServerCodec(conn))
|
||||
}
|
||||
}
|
||||
|
@ -1,15 +1,21 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net"
|
||||
"net/rpc"
|
||||
"net/rpc/jsonrpc"
|
||||
)
|
||||
|
||||
func NewClient(address string) (HelloService, error) {
|
||||
conn, err := rpc.Dial("tcp", address)
|
||||
// 建立TCP连接
|
||||
conn, err := net.Dial("tcp", "localhost:1234")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
log.Fatal("net.Dial:", err)
|
||||
}
|
||||
|
||||
client := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(conn))
|
||||
|
||||
// buf := bytes.NewBuffer([]byte{})
|
||||
// gob.NewEncoder(buf).Encode(HelloRequest{Name: "test"})
|
||||
|
||||
@ -17,7 +23,7 @@ func NewClient(address string) (HelloService, error) {
|
||||
// reader := bytes.NewReader([]byte("{}"))
|
||||
// resp := HelloRequest{Name: "test"}
|
||||
// gob.NewDecoder(reader).Decode(&resp)
|
||||
return &HelloServiceClient{conn: conn}, nil
|
||||
return &HelloServiceClient{conn: client}, nil
|
||||
}
|
||||
|
||||
// 要封装原始的 不友好的rpc call
|
||||
|
Loading…
x
Reference in New Issue
Block a user