英文:
RPC using UDP in GO
问题
Unity3D网络库使用UDP,并且具有用于RPC调用的方法。我正在尝试让我的服务器使用UDP上的RPC,但遇到了一些问题。以下是我目前的基本服务器代码:
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)
}
}
以下是客户端代码:
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)
}
// 同步调用
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)
}
当我运行这些代码时,它们都只是挂起,没有任何反应。我做错了什么?
英文:
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
得分: 1
RPC over UDP(用户数据报协议)需要特殊的UDP感知处理,因为UDP套接字的特性如此。
没有连接,只是将数据报发送到一个地址。
为了让客户端得到回复,它需要设置一个监听套接字,然后将其与请求一起发送给服务器。服务器将回复发送到客户端的地址。
net/rpc对于非连接导向的传输(例如:UDP)没有任何特殊情况的处理。
我不知道有任何实现无连接RPC的Go语言包,所以你可能需要自己编写。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论