与RPC的双向通信

时间:2018-02-06 11:52:35

标签: go tcp rpc json-rpc

我目前正在实现一个RPC接口(包括客户端和服务器),关于原始TCP连接之上的某些专有产品。该文档明确要求JSON-RPC通信,它还添加了以下提示:

In <doc number>, antenna and remote device are both server and client

在界面中,客户端应该能够从服务器接收notifications,简单的json消息,而无需回复它们。

基本上,它看起来像这样:

Server ---------------------------------------------------- Client

       <------------------------ Client Initiate Connection
       Server acknowledge connection opened -------------->

       Server sends a notification about some event------->
       Server sends another notif. about another event---->

       <---------------------------- Client Stop Connection
       Server acknowledge connection stopped ------------->

执行简单的请求/响应事件非常简单:

服务器如下所示:

func (l *Listener) GetLine(line []byte, ack *bool) error {
    fmt.Println(string(line))
    return nil
}

func main() {
    addy, err := net.ResolveTCPAddr("tcp", "0.0.0.0:42586")
    inbound, _:= net.ListenTCP("tcp", addy)
    listener := new(Listener)
    rpc.Register(listener)
    rpc.Accept(inbound)
}

客户端可以调用服务器函数

client, err := rpc.Dial("tcp", "localhost:42586")
in := bufio.NewReader(os.Stdin)
for {
    line, _, err := in.ReadLine()
    var reply bool
    client.Call("Listener.GetLine", line, &reply)
}

在这种情况下,我看不出如何将数据从服务器发送到客户端。如何使用相同的TCP连接执行此操作?它们如何既是服务器又是客户端?

0 个答案:

没有答案
相关问题