JSONRPC服务器返回空结果

huangapple go评论80阅读模式
英文:

JSONRPC server returns empty result

问题

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

package main

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

谢谢

英文:

I've coded a simple JSONRPC server to test Go's capabilities, but I'm stuck, always getting an empty result, without error and correct id. I've got the following Go code:
package main

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))
    }
}

No matter what I tried, I've always got the following response:

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

Logging shows everything is working as it should in the server.

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

Any ideas on what's going on? I'm using the latest stable version of Go, v1.1.1

Thanks

答案1

得分: 4

你的回复是指向字符串的指针类型。这是可以的,甚至是必需的,因为第二个参数用于返回答案。但是你接着做了以下操作:

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

这相当于:

  • 构造一个新的字符串并赋予一个新的值。
  • 让reply指向这个新的字符串。

这样做不会对返回的字符串产生任何影响。
尝试一下:

*reply = s
英文:

Your reply is of type pointer to string. That is okay and even required as the second argument is used to return the answer. But then you do:

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

Which translates to:

  • Construct a new string with a new value.
  • Let reply point to this new string

This lets the string which is returned completely unaffected.
Try

*reply = s

huangapple
  • 本文由 发表于 2013年7月18日 02:23:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/17707365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定