Menu Close

Go – How to close TCP connection in Go

Here, we will help you to understand how to close TCP connection in Go. We will learn about Close() method of net package by example and program.

Close() method of net package is used to close the TCP connection in Go.

Function prototype:

func (c *IPConn) Close() error

Return value:

Close() function in net package returns nil if connection closes successfully else error message.

Example with code:

package main

import (
        "fmt"
        "net"
)

func CheckCloseConnection() (error) {
        addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
        if err != nil {
                return err
        }

        l, err := net.ListenTCP("tcp", addr)
        if err != nil {
                return err
        }
        return l.Close()
}

func main() {
        if CheckCloseConnection() != nil {
            fmt.Println("There is an error in connection closing")
        } else {
            fmt.Println("Connection closes successfully")
        }
}

Output:

$ go run sample.go

Connection closes successfully

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org

Posted in golang, net

Leave a Reply

Your email address will not be published. Required fields are marked *