服务器端 udpserver.go
// udpServer project main.go
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println("udpserver")
socket, err := net.ListenUDP("udp4", &net.UDPAddr{
IP: net.IPv4(0, 0, 0, 0),
Port: 8080,
})
if err != nil {
fmt.Println("listern ", err)
return
}
defer socket.Close()
for {
data := make([]byte, 20)
read, remoteAddr, err := socket.ReadFromUDP(data)
if err != nil {
fmt.Println("read data ", err)
continue
}
fmt.Println(read, remoteAddr)
fmt.Printf("%s\n", data)
send_data := []byte("hi client!")
_, err = socket.WriteToUDP(send_data, remoteAddr)
if err != nil {
return
fmt.Println("send fail!", err)
}
}
}
客户端 udpclient.go
// udpClient project main.go
package main
import (
"fmt"
"net"
)
func main() {
fmt.Println("udpClient")
socket, err := net.DialUDP("udp4", nil, &net.UDPAddr{
IP: net.IPv4(127, 0, 0, 1),
Port: 8080,
})
if err != nil {
fmt.Println("connect fail !", err)
return
}
defer socket.Close()
senddata := []byte("hi server!")
_, err = socket.Write(senddata)
if err != nil {
fmt.Println("send fail !", err)
return
}
data := make([]byte, 20)
read, remoteAddr, err := socket.ReadFromUDP(data)
if err != nil {
fmt.Println("read fail !", err)
return
}
fmt.Println(read, remoteAddr)
fmt.Printf("%s\n", data)
}
服务器端运行:go run main.go
udpserver
10 127.0.0.1:61748
hi server!
客户端运行:go run main.go
udpClient
10 127.0.0.1:8080
hi client!