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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制