【发布时间】:2013-12-21 07:26:53
【问题描述】:
我正在尝试使用 Go 中的 RPC 调用使最小的应用程序正常工作。我从online example 大量借用,从我的代码中可以看出:
server.go:
package main
import (
[...]
)
type InfoDumper int
func (s *InfoDumper) Dump(request string, reply *string) error {
fmt.Println("Woooh imma deliverin stuff\n")
current_time := time.Now()
h:= sha1.New()
var barray []byte
copy(barray, request)
hash_rq := h.Sum(barray)
*reply = request + "\n" + current_time.Format(time.ANSIC) + "\n" + string(hash_rq) + "\n"
return nil
}
func main() {
server := new(InfoDumper)
rpc.Register(server)
rpc.HandleHTTP()
l, e := net.Listen("tcp", "127.0.0.1:40000")
if e != nil {
fmt.Println(e)
}
http.Serve(l, nil)
}
client.go:
package main
import (
[...]
)
func main() {
client, e := rpc.Dial("tcp", "127.0.0.1:40000")
if e!=nil {
fmt.Println(e)
} else {
fmt.Println("wooh server is ok")
}
in:= bufio.NewReader(os.Stdin)
for {
line, _, _ := in.ReadLine()
request := string(line)
var reply string
e = client.Call("InfoDumper.Dump", request, &reply)
if (e!=nil) {
fmt.Println("omg error!", e)
}
fmt.Println(reply)
}
}
我能看到的唯一区别是我写了 http.Serve(l, nil) 而不是 go http.Serve(l, nil) ;这是因为使用go 编写会使我的服务器立即终止。
InfoDump 应该回复发送的任何内容、请求的时间和哈希值的副本。
这就是现在发生的事情:
- 我在终端中运行 server.go
- 我在另一个终端运行 client.go,大约一秒钟后打印“wooh server is ok”
- 我输入一些内容并在客户端按 Enter 键
- 要么什么都没有发生,要么在客户端打印“rpc: client protocol error: unexpected EOF”
- 如果什么都没发生,终止服务器(即按 Control-C)会使客户端打印上面的错误
在任何一种情况下,“Woooh imma Deliverin stuff”都不会显示在服务器端...
这是在课堂上完成的,作为在进行更严肃的练习之前熟悉 Go 中的 RPC 的初步步骤;所有其他学生都设法完成了这一步,查看了这段代码,看不出与他们的区别。
有人发现这段代码有什么问题吗?
【问题讨论】:
-
第一步:不要忽略ReadLine返回的错误。
-
@Volker:为简洁起见,将大部分错误检查出来;对于 ReadLine(以及所有其他调用,除了 client.Call),不会返回错误 (==nil)。