共计 1361 个字符,预计需要花费 4 分钟才能阅读完成。
创立工程文件
mkdir udpServer udpClient
cd udpServer && go mod init udpServer && touch server.go
cd ../udpClient && go mod init udpClient && touch client.go
服务端
// server.go
package main
import(
"net"
"fmt"
)
func main(){addr, err := net.ResolveUDPAddr("udp", ":8080")
if err!=nil{panic(err)
}
fmt.Println("udp address resolve success:", addr)
udpSocket, err := net.ListenUDP("udp", addr)
if err!=nil{panic(err)
}
fmt.Println("udp socket create success...")
defer udpSocket.Close()
buf := make([]byte, 2048)
n, clientUDPAddr, err := udpSocket.ReadFromUDP(buf)
if err!=nil{panic(err)
}
fmt.Println("the client addr is:", clientUDPAddr)
fmt.Printf("receive from %s is: %s\n", clientUDPAddr, buf[:n])
_, err = udpSocket.WriteToUDP([]byte("Data processing completed!"), clientUDPAddr)
if err != nil{panic(err)
}
}
$ go run server.go
udp address resolve success: :8080
udp socket create success...
客户端
// client.go
package main
import(
"net"
"fmt"
)
func main(){conn, err := net.Dial("udp", ":8080")
if err != nil{panic(err)
}
defer conn.Close()
fmt.Println("connect to udp server 8080 ...")
conn.Write([]byte("hello, my friend..."))
buf := make([]byte, 2048)
n, err := conn.Read(buf)
if err != nil{panic(err)
}
fmt.Printf("receive from server: %s\n", buf[:n])
}
$ go run client.go
connect to udp server 8080...
测试
$ go run client.go
connect to udp server 8080 ...
receive from server: Data processing completed!
$ go run server.go
udp address resolve success: :8080
udp socket create success...
the client addr is: 127.0.0.1:48313
receive from 127.0.0.1:48313 is: hello, my friend...
正文完