style: using is struct to handle all judgements global envs
This commit is contained in:
@@ -15,12 +15,9 @@ var (
|
||||
isConnected bool
|
||||
recvChan chan string
|
||||
stopRecvChan chan struct{}
|
||||
recvWg sync.WaitGroup
|
||||
)
|
||||
|
||||
func notifyMessage(message string) {
|
||||
postLog.Info(fmt.Sprintf("%s", message))
|
||||
}
|
||||
|
||||
func Init() error {
|
||||
tcpConnMutex.Lock()
|
||||
defer tcpConnMutex.Unlock()
|
||||
@@ -53,6 +50,7 @@ func tcpConnect(ipaddr string, port int) error {
|
||||
tcpConn = conn
|
||||
isConnected = true
|
||||
|
||||
recvWg.Add(1)
|
||||
go recvMsg()
|
||||
|
||||
return nil
|
||||
@@ -66,7 +64,7 @@ func sendMsg(message string, target int) (string, error) {
|
||||
return "", fmt.Errorf("not connected")
|
||||
}
|
||||
|
||||
_, err := tcpConn.Write([]byte(message + "\n"))
|
||||
_, err := tcpConn.Write([]byte(message))
|
||||
if err != nil {
|
||||
tcpConnMutex.Unlock()
|
||||
return "", fmt.Errorf("failed to send message: %v", err)
|
||||
@@ -83,13 +81,23 @@ func sendMsg(message string, target int) (string, error) {
|
||||
}
|
||||
|
||||
func recvMsg() {
|
||||
reader := bufio.NewReader(tcpConn)
|
||||
defer recvWg.Done()
|
||||
|
||||
for {
|
||||
tcpConnMutex.Lock()
|
||||
if tcpConn == nil {
|
||||
tcpConnMutex.Unlock()
|
||||
return
|
||||
}
|
||||
conn := tcpConn
|
||||
tcpConnMutex.Unlock()
|
||||
|
||||
select {
|
||||
case <-stopRecvChan:
|
||||
return
|
||||
default:
|
||||
tcpConn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
conn.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
|
||||
reader := bufio.NewReader(conn)
|
||||
line, err := reader.ReadString('\n')
|
||||
if err != nil {
|
||||
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
|
||||
@@ -118,7 +126,7 @@ func recvMsg() {
|
||||
}
|
||||
|
||||
if len(line) > 0 && line != "success" && !isResponseMessage(line) {
|
||||
notifyMessage(line)
|
||||
postLog.Debug(fmt.Sprintf("[Watchdog] TCP Socket received message: %s", line))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,17 +137,21 @@ func isResponseMessage(msg string) bool {
|
||||
return msg == "success" || msg == "failed"
|
||||
}
|
||||
|
||||
|
||||
|
||||
func Destroy() error {
|
||||
tcpConnMutex.Lock()
|
||||
defer tcpConnMutex.Unlock()
|
||||
|
||||
if stopRecvChan != nil {
|
||||
close(stopRecvChan)
|
||||
stopRecvChan = nil
|
||||
}
|
||||
|
||||
tcpConnMutex.Unlock()
|
||||
|
||||
recvWg.Wait()
|
||||
|
||||
tcpConnMutex.Lock()
|
||||
defer tcpConnMutex.Unlock()
|
||||
|
||||
if tcpConn != nil {
|
||||
err := tcpConn.Close()
|
||||
tcpConn = nil
|
||||
|
||||
Reference in New Issue
Block a user