Golang TCP协议深度解析:如何实现自动重连功能?

发表时间: 2024-06-08 10:12

golang之tcp自动重连实现方法

server.go

package mainimport (    "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 + "\n"))    request = make([]byte, 1024)    }}func main() {    /*    // 方法一    // 监听端口    listener, err := net.Listen("tcp", "0.0.0.0:12345")    */    // 方法二    bindInfo := ":12345"    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.go

package mainimport (    "bufio"    "fmt"    "net"    "time")func doTask(conn net.Conn) {      for {          fmt.Fprintf(conn, "test msg\n")          msg, err := bufio.NewReader(conn).ReadString('\n')          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:12345"    // 断线自动重连的方法    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)    }}