What is the net.Accept function in Golang?

The Accept function of the net package in Golang implements the Accept method of a Listener interface and accepts incoming client connections.

To use the Accept function, we first import the net package into our program, as shown below:

import (
   "net"
)

Syntax

The syntax of the Accept function is shown below:

(l *TCPListener) Accept() (Conn, error)

Note: The Accept method must be called on an instance of a Listener interface.

Parameters

The Accept method does not take any parameters.

Return value

The Accept function returns a Conn object that represents a connection to a client and an error object.

If the Accept function is able to successfully establish a client connection, then the error object has a value of nil.

Code

The code below shows how the Accept function works in Golang.

package main
// import necessary packages
import (
"net"
"fmt"
)
func main(){
// initialize the address port number of the server
port := ":8000"
// Set up a listener on port 8000 for tcp connections
ln, err := net.Listen("tcp", port)
// check if server was successfully created
if err != nil {
fmt.Println("The following error occured", err)
} else {
// accept incoming connection requests
conn, err := ln.Accept()
// check if connection was established successfully
if err != nil {
fmt.Println("The following error occured", err)
} else {
fmt.Println("Established client connection:", conn)
}
}
}

Explanation

In the code above:

  • Lines 4-7: We import the net and fmt packages.
  • Line 12: We initialize the port number on which the Listen function will listen.
  • Line 15: We use the Listen function to create a server that listens for tcp connections on the specified port.
  • If there is an error in creating the server, the if statement in line 18 will detect the error and print the relevant message.
  • Line 23: We use the Accept function of the ln object to accept any incoming client connections. The code will be blocked until a client connects to the server.
  • If a client successfully establishes a connection with the server, then the conn object in line 23 will represent this connection and can be used for further communication. Otherwise, if there is an error, the if statement in line 26 will cause the relevant message to be printed.

Free Resources