// ============================================================================ // udpservice.go — 工具页 UDP 键值服务 // // 启动一个 UDP 服务器(端口可设置),任何客户机都可连接。协议语义: // - 客户端发送「键=值」→ 服务端存储该键值到内存; // - 客户端发送纯字符串(键名)→ 服务端回发已存值给请求方,键不存在则回发空; // - 键值存内存,服务停止即清空(不持久化); // - 工具页也可手动发送文本到指定远端。 // 来往数据通过 udp:log 事件推送给前端信息框展示。 // ============================================================================ package main import ( "context" "encoding/json" "errors" "fmt" "net" "strings" "sync" "time" ) // UDPInfo 描述一次 UDP 键值服务的运行状态,供前端展示。 type UDPInfo struct { Running bool `json:"running"` // 是否运行中 Port int `json:"port"` // 监听端口 Addr string `json:"addr"` // 监听地址 udp://0.0.0.0:port StartedAt string `json:"startedAt"` // 启动时间 Error string `json:"error"` // 最近一次错误 RxCount int64 `json:"rxCount"` // 累计接收数据包数 TxCount int64 `json:"txCount"` // 累计发送(回发/手动)数据包数 } // udpService 持有 UDP 键值服务的运行状态(全局单例,工具页调用)。 type udpService struct { mu sync.Mutex conn *net.UDPConn port int started time.Time cancel context.CancelFunc rx int64 tx int64 store map[string]string // 键值存储:key -> value } var udpSrv = &udpService{store: map[string]string{}} // udpEmit 推送一条日志给前端信息框。kind: recv / send / info。 func udpEmit(kind, line string) { if app == nil { return } app.Event.Emit("udp:log", map[string]string{"kind": kind, "line": line}) } // udpInfoLocked 生成当前状态快照(调用方须持有 mu)。 func udpInfoLocked() UDPInfo { info := UDPInfo{ Running: udpSrv.conn != nil, Port: udpSrv.port, RxCount: udpSrv.rx, TxCount: udpSrv.tx, } if udpSrv.conn != nil { info.Addr = fmt.Sprintf("udp://0.0.0.0:%d", udpSrv.port) info.StartedAt = udpSrv.started.Format("2006-01-02 15:04:05") } return info } // stopUDPServerLocked 停止当前服务并清空键值存储(调用方须持有 mu)。 // 关闭连接会使阻塞的 ReadFromUDP 立即返回,读循环检测 ctx 取消后退出。 func stopUDPServerLocked() { if udpSrv.cancel != nil { udpSrv.cancel() udpSrv.cancel = nil } if udpSrv.conn != nil { _ = udpSrv.conn.Close() udpSrv.conn = nil } udpSrv.port = 0 udpSrv.started = time.Time{} udpSrv.store = map[string]string{} // 停止即清空 } // udpReadLoop 阻塞读 UDP 数据包并处理键值协议,直到连接关闭。 func udpReadLoop(ctx context.Context, conn *net.UDPConn) { buf := make([]byte, 64*1024) for { n, remote, err := conn.ReadFromUDP(buf) if err != nil { if ctx.Err() != nil { return // 正常停止 } udpEmit("info", fmt.Sprintf("读取错误: %v", err)) continue } raw := string(buf[:n]) line := strings.TrimSpace(raw) if line == "" { continue // 空数据包忽略 } // 含「=」→ 存储键值;否则 → 查询并回发 if i := strings.IndexByte(line, '='); i >= 0 { key := line[:i] val := line[i+1:] udpSrv.mu.Lock() udpSrv.store[key] = val udpSrv.rx++ udpSrv.mu.Unlock() udpEmit("recv", fmt.Sprintf("%s 存储 %s=%s <- %s", time.Now().Format("15:04:05"), key, val, remote)) } else { key := line udpSrv.mu.Lock() val := udpSrv.store[key] // 不存在返回空串 udpSrv.rx++ udpSrv.mu.Unlock() // 回发结果给请求方 if _, err := conn.WriteToUDP([]byte(val), remote); err != nil { udpEmit("info", fmt.Sprintf("回发 %s 失败: %v", key, err)) continue } udpSrv.mu.Lock() udpSrv.tx++ udpSrv.mu.Unlock() disp := val if disp == "" { disp = "(空)" } udpEmit("send", fmt.Sprintf("%s 查询 %s -> %s -> %s", time.Now().Format("15:04:05"), key, disp, remote)) } } } // UDPService 是 UDP 键值服务的 Wails 服务。 type UDPService struct{} // NewUDPService 创建 UDP 服务实例。 func NewUDPService() *UDPService { return &UDPService{} } // StartUDPServer 启动 UDP 键值服务器,监听 0.0.0.0:port。 // 若已运行则先停止旧实例,并清空键值存储。端口占用时返回错误。 func (s *UDPService) StartUDPServer(port int) (UDPInfo, error) { if port < 1 || port > 65535 { return UDPInfo{}, fmt.Errorf("端口无效: %d(范围 1-65535)", port) } udpSrv.mu.Lock() stopUDPServerLocked() // 幂等先停旧实例(含清空 store) udpSrv.mu.Unlock() udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("0.0.0.0:%d", port)) if err != nil { return UDPInfo{}, fmt.Errorf("解析地址失败: %w", err) } conn, err := net.ListenUDP("udp", udpAddr) if err != nil { return UDPInfo{}, fmt.Errorf("端口 %d 监听失败(可能被占用): %w", port, err) } ctx, cancel := context.WithCancel(context.Background()) udpSrv.mu.Lock() udpSrv.conn = conn udpSrv.port = port udpSrv.started = time.Now() udpSrv.cancel = cancel udpSrv.rx = 0 udpSrv.tx = 0 udpSrv.store = map[string]string{} // 重新启动清空 info := udpInfoLocked() udpSrv.mu.Unlock() go udpReadLoop(ctx, conn) udpEmit("info", fmt.Sprintf("%s UDP 键值服务已启动: %s", time.Now().Format("15:04:05"), info.Addr)) return info, nil } // StopUDPServer 停止当前 UDP 键值服务(未运行则无副作用),并清空键值存储。 func (s *UDPService) StopUDPServer() (UDPInfo, error) { udpSrv.mu.Lock() wasRunning := udpSrv.conn != nil stopUDPServerLocked() udpSrv.mu.Unlock() if wasRunning { udpEmit("info", fmt.Sprintf("%s UDP 键值服务已停止(键值存储已清空)", time.Now().Format("15:04:05"))) } return udpInfoLocked(), nil } // UDPServerStatus 返回当前 UDP 键值服务状态。 func (s *UDPService) UDPServerStatus() UDPInfo { udpSrv.mu.Lock() defer udpSrv.mu.Unlock() return udpInfoLocked() } // SendUDP 手动发送文本到指定远端(addr 形如 ip:port)。 func (s *UDPService) SendUDP(addr, text string) (UDPInfo, error) { if strings.TrimSpace(addr) == "" { return UDPInfo{}, errors.New("目标地址不能为空") } udpAddr, err := net.ResolveUDPAddr("udp", strings.TrimSpace(addr)) if err != nil { return UDPInfo{}, fmt.Errorf("目标地址无效: %w", err) } conn, err := net.DialUDP("udp", nil, udpAddr) if err != nil { return UDPInfo{}, fmt.Errorf("连接目标失败: %w", err) } defer conn.Close() if _, err := conn.Write([]byte(text)); err != nil { return UDPInfo{}, fmt.Errorf("发送失败: %w", err) } udpSrv.mu.Lock() udpSrv.tx++ info := udpInfoLocked() udpSrv.mu.Unlock() disp := text if disp == "" { disp = "(空)" } udpEmit("send", fmt.Sprintf("%s 发送 %s -> %s", time.Now().Format("15:04:05"), disp, addr)) return info, nil } // UDPServerJSON 为前端提供一次调用获取完整状态的辅助(避免多次 IPC)。 func (s *UDPService) UDPServerJSON() string { udpSrv.mu.Lock() defer udpSrv.mu.Unlock() b, _ := json.Marshal(udpInfoLocked()) return string(b) }