【问题标题】:JSONRPC server returns empty resultJSONRPC 服务器返回空结果
【发布时间】:2013-07-16 10:52:49
【问题描述】:

我编写了一个简单的 JSONRPC 服务器来测试 Go 的功能,但我卡住了,总是得到一个空结果,没有错误和正确的 id。我有以下 Go 代码: 主包

import (
    "log"
    "net"
    "net/rpc"
    "net/rpc/jsonrpc"
)

type Experiment int

func (e *Experiment) Test(i *string, reply *string) error {
    s := "Hello, " + *i
    reply = &s
    log.Println(s, reply)
    return nil
}

func main() {
    exp := new(Experiment)
    server := rpc.NewServer()
    server.Register(exp)
    l, err := net.Listen("tcp", ":1234")
    if err != nil {
        log.Fatal("listen error:", err)
    }
    for {
        conn, err := l.Accept()
        if err != nil {
            log.Fatal(err)
        }
        server.ServeCodec(jsonrpc.NewServerCodec(conn))
    }
}

无论我尝试什么,我总是得到以下响应:

{"id":1,"result":"","error":null}

日志显示一切都在服务器中正常运行。

2013/07/17 15:17:13 Hello, Paulo 0xc200090ac0

对正在发生的事情有任何想法吗?我正在使用最新的稳定版 Go,v1.1.1

谢谢

【问题讨论】:

    标签: json go rpc


    【解决方案1】:

    您的回复是指向字符串的类型指针。这没关系,甚至是必需的,因为第二个参数用于返回答案。但是你这样做:

    s := "Hello, " + *i
    reply = &s
    

    翻译为:

    • 用新值构造一个新字符串。
    • 让回复指向这个新字符串

    这使得返回的字符串完全不受影响。 试试

    *reply = s
    

    【讨论】:

    • 哼,太好了!我应该稍微研究一下指针,因为这是我第一次尝试使用这种语言。我还不能投票,但稍后会。感谢您花时间解释!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 1970-01-01
    • 2012-07-07
    • 1970-01-01
    相关资源
    最近更新 更多