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
Acceptmethod must be called on an instance of aListenerinterface.
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 packagesimport ("net""fmt")func main(){// initialize the address port number of the serverport := ":8000"// Set up a listener on port 8000 for tcp connectionsln, err := net.Listen("tcp", port)// check if server was successfully createdif err != nil {fmt.Println("The following error occured", err)} else {// accept incoming connection requestsconn, err := ln.Accept()// check if connection was established successfullyif 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
netandfmtpackages. - Line 12: We initialize the port number on which the
Listenfunction will listen. - Line 15: We use the
Listenfunction to create a server that listens fortcpconnections on the specified port. - If there is an error in creating the server, the
ifstatement in line 18 will detect the error and print the relevant message. - Line 23: We use the
Acceptfunction of thelnobject 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
connobject in line 23 will represent this connection and can be used for further communication. Otherwise, if there is an error, theifstatement in line 26 will cause the relevant message to be printed.