1
0

udpservice.go 7.2 KB

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