Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does tcp-keep-alive affect the tcp-close in go?

Tags:

tcp

go

I have a server, when accepting a connection, I set tcp-keep-alive for 120seconds.But when I close the connection, acctually the connection doesn't close.by netstat -anp | grep 9999, I found the state was ESTABLISHED .And the client didn't receive any error from the socket , either. I want to know will tcp-keep-alive affect the tcp-close?

PS go 1.4 centos

package main
import (
    "github.com/felixge/tcpkeepalive"
    "net"
    "runtime"
    "time"
)
func  Start() {
    tcpAddr, err := net.ResolveTCPAddr("tcp4", "127.0.0.1:9999")
    if err != nil {
        return
    }
    listener, err := net.ListenTCP("tcp", tcpAddr)
    if err != nil {
        return
    }
    for {
        conn, err := listener.AcceptTCP()
        if err != nil {
            continue
        }
        go handleClient(conn)
    }
}

func handleClient(conn *net.TCPConn) {
    kaConn, err := tcpkeepalive.EnableKeepAlive(conn)
    if err != nil {
    } else {
        kaConn.SetKeepAliveIdle(120 * time.Second)
        kaConn.SetKeepAliveCount(4)
        kaConn.SetKeepAliveInterval(5 * time.Second)
    }
    time.Sleep(time.Second * 3)
    conn.Close()
    return
}

func main() {
    runtime.GOMAXPROCS(runtime.NumCPU())
    Start()
}
like image 311
frank.lin Avatar asked Dec 01 '25 08:12

frank.lin


1 Answers

Don't use that keepalive library. It duplicates file descriptors, and fails to close them.

If you need to set KeepAlive, use the methods provided in the net package.

  • SetKeepAlive
  • SetKeepAlivePeriod

You likely don't need any extra options set, but only if you're certain you do, then you can try to apply what's needed with the appropriate syscalls.

like image 89
JimB Avatar answered Dec 04 '25 00:12

JimB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!