Golang:用于重新连接TCP客户端的递归函数...不好的主意吗?

时间:2019-02-21 01:34:54

标签: go recursion tcp

我有这个有效的TCP客户端代码。如果无法在TCP连接上进行写入或读取,它将使用递归函数tcpReconnect()创建一个新连接。

这安全吗?还是会填满RAM??可能是它试图在几天之内(周末或节假日)重新连接。该代码是监视工业计算机状态的驱动程序的一部分。

也许对此问题有更好的解决方案。我找不到一个。

PS:我不喜欢投票

package main

import (
    "fmt"
    "net"
    "time"
)

var pollTime = 1000 //ms
var host = "127.0.0.1"
var port = "11000"

func main() {
    finished := make(chan bool)
    go Driver()
    <-finished
}

func tcpReconnect() net.Conn {
    newConn, err := net.Dial("tcp", host+":"+port)
    if err != nil {
        fmt.Println("Failed to reconnect:", err.Error())
        time.Sleep(time.Millisecond * time.Duration(2000))
        newConn = tcpReconnect()
    }
    return newConn
}

func Driver() {
    var conn net.Conn
    conn, err := net.Dial("tcp", host+":"+port)
    if err != nil {
        fmt.Println("Failed to initialize Connection, trying to reconnect:", err.Error())
        conn = tcpReconnect()
    }

    for {
        _, err = conn.Write([]byte("11|5546|STATUS" + "\r\n"))
        if err != nil {
            println("Write to server failed:", err.Error())
            println("Trying reset the connection...")
            conn = tcpReconnect()
        }

        var replyBuffer = make([]byte, 256)
        _, err = conn.Read(replyBuffer)
        if err != nil {
            println("Read from server failed:", err.Error())
            println("Trying reset the connection...")
            conn = tcpReConnect()
        }

        var reply string
        for i, val := range replyBuffer {
            if val == 13 { //13 is CR and marks the end of the message
                reply = string(replyBuffer[:i])
                break
            }
        }

        fmt.Printf("reply from server=%s\n", reply)
        time.Sleep(time.Millisecond * time.Duration(pollTime))
    }
}

1 个答案:

答案 0 :(得分:0)

这是我想出的。积分归@tkausl和@ThunderCat

func Driver() {
    for {
        conn, err := net.Dial("tcp", host+":"+port)
        if err != nil {
            fmt.Println("Failed to connect:", err.Error())
            fmt.Println("Trying reset the connection...")
            time.Sleep(time.Millisecond * time.Duration(2000))
        } else {
            for {

                _, err = conn.Write([]byte("11|5546|STATUS" + "\r\n"))
                if err != nil {
                    fmt.Println("Write to server failed:", err.Error())
                    fmt.Println("Trying reset the connection...")
                    break
                }

                var replyBuffer = make([]byte, 256)
                _, err = conn.Read(replyBuffer)
                if err != nil {
                    fmt.Println("Read from server failed:", err.Error())
                    fmt.Println("Trying reset the connection...")
                    break
                }

                var reply string
                for i, val := range replyBuffer {
                    if val == 13 { //13 is CR and marks the end of the message
                        reply = string(replyBuffer[:i])
                        break
                    }
                }

                fmt.Printf("reply from server=_%s_\n", reply)
                time.Sleep(time.Millisecond * time.Duration(pollTime))
            }
        }
    }
}