How do I write a UDP server in Go?

Discovered how simple UDP is. Here is a client and server written in Go. (Error handling omitted for brevity.)

First a server. It listens for UDP packets on port 10001, and prints each message to stdout:

package main
import "net"
import "fmt"
func main() {
  ServerConn, _ := net.ListenUDP("udp", &net.UDPAddr{IP:[]byte{0,0,0,0},Port:10001,Zone:""})
  defer ServerConn.Close()
  buf := make([]byte, 1024)
  for {
    n, addr, _ := ServerConn.ReadFromUDP(buf)
    fmt.Println("Received ", string(buf[0:n]), " from ", addr)
  }
}

Now a client. It sends packets to localhost UDP port 10001, each saying “hello”:

package main
import "net"
func main() {
  Conn, _ := net.DialUDP("udp", nil, &net.UDPAddr{IP:[]byte{127,0,0,1},Port:10001,Zone:""})
  defer Conn.Close()
  Conn.Write([]byte("hello"))
}

By running the server, then running our client repeatedly, we get:

% go run server.go
Received  hello  from  127.0.0.1:55877
Received  hello  from  127.0.0.1:61029
Received  hello  from  127.0.0.1:52922
Tagged #golang, #udp, #networking.
👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

More by Jim

This page copyright James Fisher 2016. Content is not associated with my employer. Found an error? Edit this page.