41 lines
957 B
Go
41 lines
957 B
Go
|
|
package main
|
|||
|
|
|
|||
|
|
import (
|
|||
|
|
"fmt"
|
|||
|
|
"log"
|
|||
|
|
"net"
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
func main() {
|
|||
|
|
// 监听 UDP 9999,可接收任意客户端数据报
|
|||
|
|
pc, err := net.ListenPacket("udp", ":9999")
|
|||
|
|
if err != nil {
|
|||
|
|
log.Fatal(err)
|
|||
|
|
}
|
|||
|
|
defer pc.Close()
|
|||
|
|
fmt.Println("Server is listening on port 9999")
|
|||
|
|
|
|||
|
|
// 循环读取数据
|
|||
|
|
for {
|
|||
|
|
// 准备一个buf来读取包的内容
|
|||
|
|
buf := make([]byte, 1024)
|
|||
|
|
n, addr, err := pc.ReadFrom(buf)
|
|||
|
|
// 如果读取失败,则继续下一次循环
|
|||
|
|
if err != nil {
|
|||
|
|
fmt.Println("Error reading data:", err)
|
|||
|
|
continue
|
|||
|
|
}
|
|||
|
|
// 业务处理: 打印读取到的数据
|
|||
|
|
fmt.Println("Read", n, "bytes from", addr)
|
|||
|
|
fmt.Println("Data:", string(buf[:n])+"\n")
|
|||
|
|
|
|||
|
|
// 写入数据(回复客户端, 回一个包)
|
|||
|
|
_, err = pc.WriteTo([]byte("Hello, Client! I have received your message: "+string(buf[:n])+"\n"), addr)
|
|||
|
|
if err != nil {
|
|||
|
|
fmt.Println("Error writing data:", err)
|
|||
|
|
continue
|
|||
|
|
}
|
|||
|
|
fmt.Println("Written", len(buf), "bytes to", addr)
|
|||
|
|
}
|
|||
|
|
}
|