File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change @@ -98,19 +98,44 @@ func StartUDPBroadcast() {
9898 ticker := time .NewTicker (2 * time .Second )
9999 defer ticker .Stop ()
100100
101+ const maxFailCount = 3 // 最大失败次数
102+ failCount := 0 // 失败计数器
103+
104+ refreshConnection := func () {
105+ conn .Close ()
106+ conn , err = net .DialUDP ("udp" , nil , addr )
107+ if err != nil {
108+ logger .Errorf ("Failed to refresh UDP connection: %v" , err )
109+ return
110+ }
111+ }
112+
101113 for range ticker .C {
102114 data , err := json .Marshal (shared .Message )
103115 if err != nil {
104116 logger .Errorf ("Failed to marshal broadcast message: %v" , err )
117+ failCount ++
118+ if failCount >= maxFailCount {
119+ logger .Info ("Refreshing UDP connection due to consecutive failures" )
120+ refreshConnection ()
121+ failCount = 0 // 重置失败计数器
122+ }
105123 continue
106124 }
107125
108126 _ , err = conn .Write (data )
109127 if err != nil {
110128 logger .Errorf ("Failed to send UDP broadcast: %v" , err )
129+ failCount ++
130+ if failCount >= maxFailCount {
131+ logger .Info ("Refreshing UDP connection due to consecutive failures" )
132+ refreshConnection ()
133+ failCount = 0 // 重置失败计数器
134+ }
111135 continue
112136 }
113137
114138 logger .Debug ("Sent UDP broadcast" )
139+ failCount = 0 // 成功发送后重置失败计数器
115140 }
116141}
You can’t perform that action at this time.
0 commit comments