go20/day09/upd/server/main.go
2026-03-29 17:54:32 +08:00

41 lines
957 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
}
}