A Simple UDP Server in Go
Creating Go network clients and servers is simple, supported as it is by the excellent built-in net
package. But when I wanted to create a UDP server instead of a TCP or UNIX socket server, the API through me for a loop. I assumed that the same net.Listen()
function I used for other server types would work for a UDP server. But it doesn't.
Normally, net.Listen()
returns a net.Listener
. But UDP servers don't have anything that would implement the Listener
interface, since there is no acceptance step. Instead, they work directly with net.Conn
instances (actually, they're net.UDPConn
instances that implement net.Conn
). So instead of using the net.Listen()
function, you must use net.ListenUDP()
:
func myUDPServer() {
addr := net.UDPAddr{
Port: 9229,
IP: net.ParseIP("127.0.0.1"),
}
conn, err := net.ListenUDP("udp", &addr)
defer conn.Close()
if err != nil {
panic(err)
}
// Do something with `conn`
}
While a TCP or UNIX socket server must handle Listener.Accept()
events, the UDP server is directly given a handle to a net.Conn
instance which it can read from and write to directly.
While the connection returned has the Read()
/Write()
and ReadFrom()
/WriteTo()
methods familiar with other network servers, there are some specially useful UDP IO functions, such as ReadFromUDP()
and ReadMsgUDP()
/WriteMsgUDP()
. These will allow greater access to UDP protocol information.