The udp client side code udp_client.go is as follows:
package main
import (
"fmt"
"net"
"os"
)
func main() {
conn, err := net.Dial("udp", "127.0.0.1:8080")
if err != nil {
fmt.Print(err)
return
}
defer conn.Close()
go func() {
buf := make([]byte, 1024)
for {
n, err := os.Stdin.Read(buf)
if err != nil {
fmt.Println(err)
continue
}
_, _ = conn.Write(buf[:n])
}
}()
buf := make([]byte, 1024)
for {
n, err := conn.Read(buf)
if err != nil {
fmt.Print(err)
continue
}
fmt.Println(string(buf[:n]))
}
}
go build udp_client.go
The udp server side code udp_server.go is as follows:
package main
import (
"fmt"
"net"
"time"
)
func main() {
addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:8080")
if err != nil {
fmt.Println(err)
return
}
conn, err := net.ListenUDP("udp", addr)
fmt.Println("start listen...")
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
buf := make([]byte, 1024)
for {
n, clientAddr, err := conn.ReadFromUDP(buf)
fmt.Println(string(buf[:n]))
fmt.Println(clientAddr.Network(), clientAddr.String())
if err != nil {
fmt.Println(err)
continue
}
go func() {
_, err = conn.WriteToUDP([]byte(time.Now().String()), clientAddr)
if err != nil {
fmt.Println(err)
return
}
}()
}
}
go build udp_server.go