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"
)
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 aListener
interface.
The Accept
method does not take any parameters.
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
.
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)}}}
In the code above:
net
and fmt
packages.Listen
function will listen.Listen
function to create a server that listens for tcp
connections on the specified port.if
statement in line 18 will detect the error and print the relevant message.Accept
function of the ln
object to accept any incoming client connections. The code will be blocked until a client connects to the server.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.