doy51723 2012-09-16 06:17
浏览 99

使用UDPConn的请求/响应对话

I'm trying to implement the following UDP protocol, but I'm having a little trouble figuring exactly how I should approach this.

The protocol states that I should send a particular UDP packet to a certain server, after which the server will stream (several UDP packets that are related) a response back to me, also as UDP packets. I have managed to send the UDP packet fine using the following code:

connection, error := net.DialUDP("udp", nil, endpoint)
...
if written, error := connection.Write(query.ToBytes()); error != nil {
    ...
} else {
    log.Printf("Successfully wrote %d bytes to %s", written, connection.RemoteAddr())
}

When I use Wireshark and take a look at what's going over the wire, it looks like it sent the packet just fine (the only issue here is that I never get a reply from the server, but that's unrelated to this question).

What's the best way for me to handle the server reply in this case? Can I use the previously established connection to read server responses back (this seems unlikely to me, as it's UDP so connectionless) or should I use net.ListenUDP(...) to establish a server on the correct local address and port to read whatever the server sends back to me?

  • 写回答

2条回答 默认 最新

  • dreamfly2016 2012-09-16 08:24
    关注

    Because of the specific protocol design, it's impossible to know on which port the server will send its reply packets. After taking a second look at the packet dumps, I noticed that the server in fact does reply, only the client immediately replies back with an ICMP message saying Destination port unreachable. So the server was trying to reply, but it couldn't because the client would not accept the packets on that port.

    To solve this, I have used net.ListenUDP to listen for incoming packets immediately after the client sends the initial packet using the established connection's local address:

    incomingConnection, _ := net.ListenUDP("udp", connection.LocalAddr().(*net.UDPAddr))
    log.Printf("Listening for packets on %s", incomingConnection.LocalAddr())
    defer incomingConnection.Close()
    

    After which incomingConnection can be used as a Reader - for example - read the packets that the server is sending.

    评论

报告相同问题?