udpservice.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // ============================================================================
  2. // udpservice.go — 工具页 UDP 键值服务
  3. //
  4. // 启动一个 UDP 服务器(端口可设置),任何客户机都可连接。协议语义:
  5. // - 客户端发送「键=值」→ 服务端存储该键值到内存;
  6. // - 客户端发送纯字符串(键名)→ 服务端回发已存值给请求方,键不存在则回发空;
  7. // - 键值存内存,服务停止即清空(不持久化);
  8. // - 工具页也可手动发送文本到指定远端。
  9. // 来往数据通过 udp:log 事件推送给前端信息框展示。
  10. // ============================================================================
  11. package main
  12. import (
  13. "context"
  14. "encoding/json"
  15. "errors"
  16. "fmt"
  17. "net"
  18. "strings"
  19. "sync"
  20. "time"
  21. )
  22. // UDPInfo 描述一次 UDP 键值服务的运行状态,供前端展示。
  23. type UDPInfo struct {
  24. Running bool `json:"running"` // 是否运行中
  25. Port int `json:"port"` // 监听端口
  26. Addr string `json:"addr"` // 监听地址 udp://0.0.0.0:port
  27. StartedAt string `json:"startedAt"` // 启动时间
  28. Error string `json:"error"` // 最近一次错误
  29. RxCount int64 `json:"rxCount"` // 累计接收数据包数
  30. TxCount int64 `json:"txCount"` // 累计发送(回发/手动)数据包数
  31. }
  32. // udpService 持有 UDP 键值服务的运行状态(全局单例,工具页调用)。
  33. type udpService struct {
  34. mu sync.Mutex
  35. conn *net.UDPConn
  36. port int
  37. started time.Time
  38. cancel context.CancelFunc
  39. rx int64
  40. tx int64
  41. store map[string]string // 键值存储:key -> value
  42. }
  43. var udpSrv = &udpService{store: map[string]string{}}
  44. // udpEmit 推送一条日志给前端信息框。kind: recv / send / info。
  45. func udpEmit(kind, line string) {
  46. if app == nil {
  47. return
  48. }
  49. app.Event.Emit("udp:log", map[string]string{"kind": kind, "line": line})
  50. }
  51. // udpInfoLocked 生成当前状态快照(调用方须持有 mu)。
  52. func udpInfoLocked() UDPInfo {
  53. info := UDPInfo{
  54. Running: udpSrv.conn != nil,
  55. Port: udpSrv.port,
  56. RxCount: udpSrv.rx,
  57. TxCount: udpSrv.tx,
  58. }
  59. if udpSrv.conn != nil {
  60. info.Addr = fmt.Sprintf("udp://0.0.0.0:%d", udpSrv.port)
  61. info.StartedAt = udpSrv.started.Format("2006-01-02 15:04:05")
  62. }
  63. return info
  64. }
  65. // stopUDPServerLocked 停止当前服务并清空键值存储(调用方须持有 mu)。
  66. // 关闭连接会使阻塞的 ReadFromUDP 立即返回,读循环检测 ctx 取消后退出。
  67. func stopUDPServerLocked() {
  68. if udpSrv.cancel != nil {
  69. udpSrv.cancel()
  70. udpSrv.cancel = nil
  71. }
  72. if udpSrv.conn != nil {
  73. _ = udpSrv.conn.Close()
  74. udpSrv.conn = nil
  75. }
  76. udpSrv.port = 0
  77. udpSrv.started = time.Time{}
  78. udpSrv.store = map[string]string{} // 停止即清空
  79. }
  80. // udpReadLoop 阻塞读 UDP 数据包并处理键值协议,直到连接关闭。
  81. func udpReadLoop(ctx context.Context, conn *net.UDPConn) {
  82. buf := make([]byte, 64*1024)
  83. for {
  84. n, remote, err := conn.ReadFromUDP(buf)
  85. if err != nil {
  86. if ctx.Err() != nil {
  87. return // 正常停止
  88. }
  89. udpEmit("info", fmt.Sprintf("读取错误: %v", err))
  90. continue
  91. }
  92. raw := string(buf[:n])
  93. line := strings.TrimSpace(raw)
  94. if line == "" {
  95. continue // 空数据包忽略
  96. }
  97. // 含「=」→ 存储键值;否则 → 查询并回发
  98. if i := strings.IndexByte(line, '='); i >= 0 {
  99. key := line[:i]
  100. val := line[i+1:]
  101. udpSrv.mu.Lock()
  102. udpSrv.store[key] = val
  103. udpSrv.rx++
  104. udpSrv.mu.Unlock()
  105. udpEmit("recv", fmt.Sprintf("%s 存储 %s=%s <- %s", time.Now().Format("15:04:05"), key, val, remote))
  106. } else {
  107. key := line
  108. udpSrv.mu.Lock()
  109. val := udpSrv.store[key] // 不存在返回空串
  110. udpSrv.rx++
  111. udpSrv.mu.Unlock()
  112. // 回发结果给请求方
  113. if _, err := conn.WriteToUDP([]byte(val), remote); err != nil {
  114. udpEmit("info", fmt.Sprintf("回发 %s 失败: %v", key, err))
  115. continue
  116. }
  117. udpSrv.mu.Lock()
  118. udpSrv.tx++
  119. udpSrv.mu.Unlock()
  120. disp := val
  121. if disp == "" {
  122. disp = "(空)"
  123. }
  124. udpEmit("send", fmt.Sprintf("%s 查询 %s -> %s -> %s", time.Now().Format("15:04:05"), key, disp, remote))
  125. }
  126. }
  127. }
  128. // UDPService 是 UDP 键值服务的 Wails 服务。
  129. type UDPService struct{}
  130. // NewUDPService 创建 UDP 服务实例。
  131. func NewUDPService() *UDPService {
  132. return &UDPService{}
  133. }
  134. // StartUDPServer 启动 UDP 键值服务器,监听 0.0.0.0:port。
  135. // 若已运行则先停止旧实例,并清空键值存储。端口占用时返回错误。
  136. func (s *UDPService) StartUDPServer(port int) (UDPInfo, error) {
  137. if port < 1 || port > 65535 {
  138. return UDPInfo{}, fmt.Errorf("端口无效: %d(范围 1-65535)", port)
  139. }
  140. udpSrv.mu.Lock()
  141. stopUDPServerLocked() // 幂等先停旧实例(含清空 store)
  142. udpSrv.mu.Unlock()
  143. udpAddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("0.0.0.0:%d", port))
  144. if err != nil {
  145. return UDPInfo{}, fmt.Errorf("解析地址失败: %w", err)
  146. }
  147. conn, err := net.ListenUDP("udp", udpAddr)
  148. if err != nil {
  149. return UDPInfo{}, fmt.Errorf("端口 %d 监听失败(可能被占用): %w", port, err)
  150. }
  151. ctx, cancel := context.WithCancel(context.Background())
  152. udpSrv.mu.Lock()
  153. udpSrv.conn = conn
  154. udpSrv.port = port
  155. udpSrv.started = time.Now()
  156. udpSrv.cancel = cancel
  157. udpSrv.rx = 0
  158. udpSrv.tx = 0
  159. udpSrv.store = map[string]string{} // 重新启动清空
  160. info := udpInfoLocked()
  161. udpSrv.mu.Unlock()
  162. go udpReadLoop(ctx, conn)
  163. udpEmit("info", fmt.Sprintf("%s UDP 键值服务已启动: %s", time.Now().Format("15:04:05"), info.Addr))
  164. return info, nil
  165. }
  166. // StopUDPServer 停止当前 UDP 键值服务(未运行则无副作用),并清空键值存储。
  167. func (s *UDPService) StopUDPServer() (UDPInfo, error) {
  168. udpSrv.mu.Lock()
  169. wasRunning := udpSrv.conn != nil
  170. stopUDPServerLocked()
  171. udpSrv.mu.Unlock()
  172. if wasRunning {
  173. udpEmit("info", fmt.Sprintf("%s UDP 键值服务已停止(键值存储已清空)", time.Now().Format("15:04:05")))
  174. }
  175. return udpInfoLocked(), nil
  176. }
  177. // UDPServerStatus 返回当前 UDP 键值服务状态。
  178. func (s *UDPService) UDPServerStatus() UDPInfo {
  179. udpSrv.mu.Lock()
  180. defer udpSrv.mu.Unlock()
  181. return udpInfoLocked()
  182. }
  183. // SendUDP 手动发送文本到指定远端(addr 形如 ip:port)。
  184. func (s *UDPService) SendUDP(addr, text string) (UDPInfo, error) {
  185. if strings.TrimSpace(addr) == "" {
  186. return UDPInfo{}, errors.New("目标地址不能为空")
  187. }
  188. udpAddr, err := net.ResolveUDPAddr("udp", strings.TrimSpace(addr))
  189. if err != nil {
  190. return UDPInfo{}, fmt.Errorf("目标地址无效: %w", err)
  191. }
  192. conn, err := net.DialUDP("udp", nil, udpAddr)
  193. if err != nil {
  194. return UDPInfo{}, fmt.Errorf("连接目标失败: %w", err)
  195. }
  196. defer conn.Close()
  197. if _, err := conn.Write([]byte(text)); err != nil {
  198. return UDPInfo{}, fmt.Errorf("发送失败: %w", err)
  199. }
  200. udpSrv.mu.Lock()
  201. udpSrv.tx++
  202. info := udpInfoLocked()
  203. udpSrv.mu.Unlock()
  204. disp := text
  205. if disp == "" {
  206. disp = "(空)"
  207. }
  208. udpEmit("send", fmt.Sprintf("%s 发送 %s -> %s", time.Now().Format("15:04:05"), disp, addr))
  209. return info, nil
  210. }
  211. // UDPServerJSON 为前端提供一次调用获取完整状态的辅助(避免多次 IPC)。
  212. func (s *UDPService) UDPServerJSON() string {
  213. udpSrv.mu.Lock()
  214. defer udpSrv.mu.Unlock()
  215. b, _ := json.Marshal(udpInfoLocked())
  216. return string(b)
  217. }