Net package: Dialer Keep Alive field confusion

Hi there,

Recently, I am learning establish TCP client and server using Golang. I want to make sure the TCP connection will be closed for certain amount of inactive time. Therefore, I used the Dialer object, and set the KeepAlive field to the time I want. However, after doing some tests, even when both client and server do nothing, the TCP connection is still existed.

Client:

package main

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

func main(){
	d := &net.Dialer{KeepAlive: 1 * time.Second}
	fmt.Println("Launching Client ...")
	conn, err := d.Dial("tcp", "127.0.0.1:8081")
	time.Sleep(10 * time.Second)
	fmt.Println("Connection Established ...")
	if err != nil {
		fmt.Println("Error:", err)
	}
	// Sending message every second
	for {
		text := "Send a test to server through TCP"
		time.Sleep(time.Second)
		// send to socket
		_, err := fmt.Fprintf(conn, text + "\n")
		if err != nil {
			fmt.Println("ERROR:", err)
		}
	}
}

Server:

package main

import "net"
import "fmt"
import "bufio"
// only needed below for sample processing

func main() {

	fmt.Println("Launching server...")

	// listen on all interfaces
	ln, _ := net.Listen("tcp", ":8081")

	// accept connection on port
	conn, _ := ln.Accept()

	// run loop forever (or until ctrl-c)
	for {
		// will listen for message to process ending in newline (\n)
		message, _ := bufio.NewReader(conn).ReadString('\n')
		// output message received
		fmt.Print("Message Received:", string(message))
		// sample process for string received
		//newmessage := strings.ToUpper(message)
		//// send new string back to client
		//conn.Write([]byte(newmessage + "\n"))
	}
}

any help is appreciated. Thank you.

Do you send something from the client or don’t you? Is this the complete code you use?

Instead keep-alives you can use conn.SetReadDeadline (on the server side), conn.SetWriteDeadline (on the client side).

BTW, you also need to keep setting them again and again whenever an activity occurs. When you don’t set them, they will timeout if nothing happens in the given timeframe. When they timeout and you want to read from or write to the connection, you will get a timeout error, then you would have to close the connection by yourself (it’s because the behavior is system-dependent).

Thanks for replying. Client sent message to server every second. However, before it starts to send messages, I let it sleep for 10 seconds, which exceeds the KeepAlive time I specified for the Dialer. Yes, this is the complete codes I have.

Thanks for your help. I am wondering the meaning of “KeepAlive” field specified in the Dialer. Based on my understanding, “KeepAlive” field specifies how long the connection will open in a certain time period. After the time I specified, the connection will be died, and communications between client and server will be prohibited unless re-establish the connection.

I am wondering the meaning of “KeepAlive” field specified in the Dialer. Based on my understanding, “KeepAlive” field specifies how long the connection will open in a certain time period. After the time I specified, the connection will be died, and communications between client and server will be prohibited unless re-establish the connection.

No, it’s not like that. Keep-Alive is used as a low-level mechanism to detect whether one of the parties are still there or not. But, you can’t use keep-alive option to detect whether the connected parties ever talked. Read more here.

I want to make sure the TCP connection will be closed for certain amount of inactive time.

In your case, your goal is to drop the connection after a certain time threshold is reached. To do that, you need to build a heartbeat mechanism. So, you can use XXXDeadline functions to build that mechanism easily. Or you can use your own timer, it depends on you.

1 Like

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