Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created January 16, 2019 06:19
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miguelmota/01ba5131838ae31947ac9b03e57f3773 to your computer and use it in GitHub Desktop.
Save miguelmota/01ba5131838ae31947ac9b03e57f3773 to your computer and use it in GitHub Desktop.
Golang UDP server example
echo 'hello world' > /dev/udp/0.0.0.0/3000
package main
import (
"fmt"
"net"
"strings"
)
func main() {
conn, err := net.ListenUDP("udp", &net.UDPAddr{
Port: 3000,
IP: net.ParseIP("0.0.0.0"),
})
if err != nil {
panic(err)
}
defer conn.Close()
fmt.Printf("server listening %s\n", conn.LocalAddr().String())
for {
message := make([]byte, 20)
rlen, remote, err := conn.ReadFromUDP(message[:])
if err != nil {
panic(err)
}
data := strings.TrimSpace(string(message[:rlen]))
fmt.Printf("received: %s from %s\n", data, remote)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment