goudp

UDP in golang, Listen not a blocking call?


I'm trying to create a two way street between two computers using UDP as a protocol. Maybe I'm not understanding the point of net.ListenUDP. Shouldn't this be a blocking call? Waiting for a client to connect?

addr := net.UDPAddr{
    Port: 2000,
    IP:   net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr)
// code does not block here
defer conn.Close()
if err != nil {
    panic(err)
}

var testPayload []byte = []byte("This is a test")

conn.Write(testPayload)

Solution

  • It isn't blocking because it runs in the background. Then you just read from the connection.

    addr := net.UDPAddr{
        Port: 2000,
        IP:   net.ParseIP("127.0.0.1"),
    }
    conn, err := net.ListenUDP("udp", &addr) // code does not block here
    if err != nil {
        panic(err)
    }
    defer conn.Close()
    
    var buf [1024]byte
    for {
        rlen, remote, err := conn.ReadFromUDP(buf[:])
        // Do stuff with the read bytes
    }
    
    
    var testPayload []byte = []byte("This is a test")
    
    conn.Write(testPayload)
    

    Check this answer. It has a working example of UDP connections in go and some tips to make it work a little better.