1 server.go
package main
import (
"fmt"
"net"
)
func main() {
listen, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: 9090,
})
if err != nil {
return
}
for {
var data [1024]byte
n, addr, err := listen.ReadFromUDP(data[:])
if err != nil {
break
}
go func() {
fmt.Printf("addr:%v data:%v count:%v\n", addr, string(data[:n]), n)
_, err = listen.WriteToUDP([]byte("received success!"), addr)
}()
}
}
2 client.go
package main
import (
"fmt"
"net"
"time"
)
func main() {
conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
IP: net.IPv4(192, 168, 1, 103),
Port: 9090,
})
if err != nil {
return
}
go func() {
for {
var data [1024]byte
n, addr, _ := conn.ReadFromUDP(data[:])
fmt.Printf("addr:%v data:%v count:%v\n", addr, string(data[:n]), n)
}
}()
for i := 0; i < 100; i++ {
fmt.Print("hi")
_, err := conn.Write([]byte("hello server!"))
if err != nil {
return
}
}
time.Sleep(time.Hour)
}