Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP in golang, Listen not a blocking call?

Tags:

go

udp

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)
like image 742
Jonathan Eustace Avatar asked Nov 27 '14 17:11

Jonathan Eustace


1 Answers

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 ln.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.

like image 190
Topo Avatar answered Oct 10 '22 23:10

Topo