douliang6563 2014-11-14 23:31
浏览 230
已采纳

在GO中使用UDP进行RPC

Unity3D networking libraries use UDP and has methods for RPC calls. I'm trying to get my server to use RPC over UDP and I'm having some trouble. Here's the basic server code I've got now:

type Args struct {
  X, Y int
}

type RequestHandler struct{}

func (self *RequestHandler) Add(args *Args, reply *int) error {
  *reply = args.X + args.Y
  return nil
}

func main() {
  addr := net.UDPAddr{ Port: 5127, IP: net.ParseIP("127.0.0.1") } 
  handler := new(RequestHandler)

  rpc.Register(handler)
  conn, err := net.ListenUDP("udp", &addr)
  defer conn.Close()

  if err != nil {
    panic(err)
  }

  for {
    go rpc.ServeConn(conn)
  }
}

And here is the client code:

type Args struct {
  X, Y int
}

func main() {
  client, err := rpc.Dial("udp", "127.0.0.1:5127")
  if err != nil { log.Fatal("dialing:", err) }

  // Synchronous call
  args := &Args{7,8}
  var reply int
  err = client.Call("RequestHandler.Add", args, &reply)
  if err != nil {
    log.Fatal("arith error:", err)
  }

  fmt.Printf("Result: %d + %d = %d", args.X, args.Y, reply)
}

When I run these, they both just hang, nothing happens. What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dsfg3241 2014-11-15 02:49
    关注

    RPC over UDP requires special UDP aware handling due to the nature of UDP sockets.

    There is no connection, just datagrams sent to an address.

    For the client to get a reply, it would have to set up a listening socket and then send that to the server along with the request. The server would then reply to the clients address.

    net/rpc doesn't have any special case handling for non-connection oriented transports (ie: UDP)

    I don't know of any packages that implement connection-less RPC for go, so you may have to roll your own here.

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

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换