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
I wrote this because I felt like it. This post is my own, and not associated with my employer.
Jim. Public speaking. Friends. Vidrio.