SoFunction
Updated on 2025-03-05

Golang's TCP automatic reconnection implementation method

Operating system: CentOS 6.9_x64

Go language version: 1.8.3

Problem description

There is an existing tcp client program that needs to retrieve data from the server regularly, but it needs to be automatically reconnected due to various reasons (network instability, etc.).

Test server sample code:

/*
tcp server for test

*/


package main

import (
  "fmt"
  "net"
  "os"
  "strings"
  "time"
)

func checkError(err error) {
  if err != nil {
    (err)
    (1)
  }
}

func handleClient(conn ) {
  (().Add(3 * ))
  request := make([]byte,1024)
  defer ()

  for {
    recv_len,err := (request)
    if err != nil {
      (err)
      break
    }
    if recv_len == 0 {
      break
    }
    recvData := (string(request[:recv_len]))
    ("recv_len : ",recv_len)
    ("recv_data : " + recvData)
    daytime := ().String()
    ([]byte(daytime + "\n"))
    request = make([]byte,1024)
  }
}

func main() {
  bindInfo := ":12345"
  tcpAddr,err := ("tcp4",bindInfo)
  checkError(err)
  listener,err := ("tcp",tcpAddr)
  checkError(err)
  for {
    cc,err := ()
    if err != nil {
      continue
    }
    go handleClient(cc)
  }
}

Solution

/*
tcp client with reconnect

*/

package main

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

func doTask(conn ) {
  for {
    (conn,"test msg\n")
    msg,err := (conn).ReadString('\n')
    if err != nil {
      ("recv data error")
      break
    }else{
      ("recv msg : ",msg)
    }
    (1 * )
  }

}

func main() {
  hostInfo := "127.0.0.1:12345"

  for {
    conn,err := ("tcp",hostInfo)
    ("connect (",hostInfo)
    if err != nil {
      (") fail")
    }else{
      (") ok")
      defer ()
      doTask(conn)
    }
    (3 * )
  }
}

Running effect:

[root@local t1]# ./tcpClient1
connect (127.0.0.1:12345) ok
recv msg : 2017-06-12 21:10:32.110977137 +0800 CST

recv msg : 2017-06-12 21:10:33.111868746 +0800 CST

recv data error
connect (127.0.0.1:12345) fail
connect (127.0.0.1:12345) fail
connect (127.0.0.1:12345) ok
recv msg : 2017-06-12 21:10:43.117203432 +0800 CST

recv msg : 2017-06-12 21:10:44.11853427 +0800 CST

discuss

This is just a simple example code that implements automatic reconnection of tcp.

OK, that's all, I hope it will be helpful to you.

The above article "TCP automatic reconnection implementation method" of Golang is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.