堕落不振功业废,勤耕不辍日月新

golang TCP client自动重连

Python hailen 42℃

golang简易版TCP client server 篇中简单列了下golang下的c/s模式代码,不过遇到 server 端异常时, client端也就自动退出了,这里再给出一段自动重连的代码,实现无论server端如何,client始装循环下去。所以本篇的重点是client端的代码

server 端代码

package main
import (
    "fmt"
    "net"
    "os"
    "strings"
    "time"
)
func checkError(err error) {
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}
func handleClient(conn net.Conn) {
    conn.SetReadDeadline(time.Now().Add(3 * time.Minute))
    request := make([]byte,1024)
    defer conn.Close()
    for {
        recv_len,err := conn.Read(request)
        if err != nil {
            fmt.Println(err)
            break
        }
        if recv_len == 0 {
            break
        }
        recvData := strings.TrimSpace(string(request[:recv_len]))
        fmt.Println("recv_len : ",recv_len)
        fmt.Println("recv_data : " + recvData)
        daytime := time.Now().String()
        conn.Write([]byte(daytime + "
"))
        request = make([]byte,1024)
    }
}
func main() {
    bindInfo := ":10000"
    tcpAddr,err := net.ResolveTCPAddr("tcp4",bindInfo)
    checkError(err)
    listener,err := net.ListenTCP("tcp",tcpAddr)
    checkError(err)
    for {
        cc,err := listener.Accept()
        if err != nil {
            continue
        }
        go handleClient(cc)
    }
}

client端代码

package main
import (
    "net"
    "fmt"
    "bufio"
    "time"
)
func doTask(conn net.Conn) {
    for {
        fmt.Fprintf(conn,"test msg
")
        msg,err := bufio.NewReader(conn).ReadString('
')
        if err != nil {
            fmt.Println("recv data error")
            break
        }else{
            fmt.Println("recv msg : ",msg)
        }
        time.Sleep(1 * time.Second)
    }
}
func main() {
    hostInfo := "127.0.0.1:10000"
    for {
        conn,err := net.Dial("tcp",hostInfo)
        fmt.Print("connect (",hostInfo)
        if err != nil {
            fmt.Println(") fail")
        }else{
            fmt.Println(") ok")
            defer conn.Close()
            doTask(conn)
        }
        time.Sleep(3 * time.Second)
    }
}

具体运行效果我就不再黏了。

后记:另外需要注意一点的是,如果有用到log模块,需要特别注意 log.Fatal和log.Panic类方法,具体可以参看我的另一篇博文 golang下慎用log.Fatal和log.Panic

golang TCP client自动重连,首发于运维之路

转载请注明:我是IT » golang TCP client自动重连

喜欢 (0)or分享 (0)