From 6fcf57b46706544947a6f721d5d524b0160ad6e0 Mon Sep 17 00:00:00 2001 From: sanxun0325 Date: Fri, 7 May 2021 20:21:16 +0800 Subject: [PATCH] refine code --- clients/naming_client/push_receiver.go | 28 +++++++++----------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/clients/naming_client/push_receiver.go b/clients/naming_client/push_receiver.go index dc5f6d4d..9b2ac882 100644 --- a/clients/naming_client/push_receiver.go +++ b/clients/naming_client/push_receiver.go @@ -70,9 +70,8 @@ func (us *PushReceiver) tryListen() (*net.UDPConn, bool) { return conn, true } -func (us *PushReceiver) startServer() { +func (us *PushReceiver) getConn() *net.UDPConn { var conn *net.UDPConn - for i := 0; i < 3; i++ { r := rand.New(rand.NewSource(time.Now().UnixNano())) port := r.Intn(1000) + 54951 @@ -82,14 +81,18 @@ func (us *PushReceiver) startServer() { if ok { conn = conn1 logger.Infof("udp server start, port: " + strconv.Itoa(port)) - break + return conn } if !ok && i == 2 { logger.Errorf("failed to start udp server after trying 3 times.") } } + return nil +} +func (us *PushReceiver) startServer() { + conn := us.getConn() go func() { defer func() { if conn != nil { @@ -106,22 +109,9 @@ func (us *PushReceiver) handleClient(conn *net.UDPConn) { if conn == nil { time.Sleep(time.Second * 5) - for i := 0; i < 3; i++ { - r := rand.New(rand.NewSource(time.Now().UnixNano())) - port := r.Intn(1000) + 54951 - us.port = port - conn1, ok := us.tryListen() - - if ok { - conn = conn1 - logger.Infof("udp server start, port: " + strconv.Itoa(port)) - break - } - - if !ok && i == 2 { - logger.Errorf("failed to start udp server") - return - } + conn = us.getConn() + if conn == nil { + return } }