drbxr86044 2014-03-21 00:38
浏览 85
已采纳

当我的客户端连接时,简单的RPC服务器将无法应答

I took and adapted the example from Golang RPC to make a simple RPC server as a test run for the real task I want to acheive. But whatever I have tried I end up with the client getting

2014/03/21 13:28:41 dialing: dial-http tcp MYPC:61740: unexpected HTTP response: 404 Not Found

I have tried using MYPC:0, 127.0.0.1:61470, MYPC:61470 and other variants of that theme for the server. Also have tried locally and on two different computers (Note I am using Go 1.2 on Windows). Usually with Go I find it straight-forward to debug, but even reading the source for the rpc pacakge is not helping this time - however I did pick up the trick of :0 giving an available port.

Server can be run by just running the exe, and Client can be run with the port output by the server chat -c -server=127.0.0.1:8082.

What is actually wrong with the following code?

package main

import (
"flag"
"log"
"net"
"net/http"
"net/rpc"
)

type Chat string

func (t *Chat) Msg(msg string, bytes *int) error {
    *bytes = len(msg)
    return nil
}

func main() {

    server := flag.String("server", "", "Server and port")
    client := flag.Bool("c", false, "Make me a client")
    flag.Parse()

    log.Println("Server: ", *server)

    if !(*client) {

        chat := new(Chat)
        rpc.Register(chat)
        l, e := net.Listen("tcp", *server)
        if e != nil {
            log.Fatal("listen error:", e)
        }
        log.Println(l.Addr().String())
        go rpc.Accept(l)
        http.Serve(l, nil)

    } else {

        log.Println("Client connecting to", *server)
        // !! The error occurs here
        client, err := rpc.DialHTTP("tcp", *server)
        if err != nil {
            log.Fatal("dialing: ", err)
        }

        var reply int
        err = client.Call("Chat.Msg", "Make it so!", &reply)
        if err != nil {
            log.Fatal("chat error:", err)
        }
        log.Println("Msg: returned", reply)
}
}
  • 写回答

1条回答 默认 最新

  • dongwen3093 2014-03-21 01:34
    关注

    I think you're missing rpc.HandleHTTP() after rpc.Register(chat). Try changing your code to

    ...
    rpc.Register(chat)
    rpc.HandleHTTP()
    ...
    

    It worked for me this way, I got

    2014/03/20 18:31:21 Server:  localhost:55209
    2014/03/20 18:31:21 Client connecting to localhost:55209
    2014/03/20 18:31:21 Msg: returned 11
    

    And you don't need go rpc.Accept(l). At least for me it worked without this line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog