weather-station/main.go

47 lines
925 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"
"weatherstation/config"
"weatherstation/model"
)
func main() {
cfg := config.GetConfig()
addr := fmt.Sprintf(":%d", cfg.Server.UDPPort)
conn, err := net.ListenPacket("udp", addr)
if err != nil {
log.Fatalf("无法监听UDP端口 %d: %v", cfg.Server.UDPPort, err)
}
defer conn.Close()
log.Printf("UDP服务器已启动监听端口 %d...", cfg.Server.UDPPort)
buffer := make([]byte, 2048)
for {
n, addr, err := conn.ReadFrom(buffer)
if err != nil {
log.Printf("读取数据错误: %v", err)
continue
}
data := string(buffer[:n])
log.Printf("从 %s 接收到 %d 字节数据", addr.String(), n)
weatherData, err := model.ParseWeatherData(data)
if err != nil {
log.Printf("解析数据失败: %v", err)
log.Printf("原始数据: %s", data)
continue
}
fmt.Println("成功解析气象站数据:")
fmt.Println(weatherData)
}
}