The Listen
function of the net
package in Go creates servers and listens for incoming connections on a local network address.
To use the Listen
function, we’ll import the net
package into our program as shown below:
import (
"net"
)
The syntax of the Listen
function is shown below:
Listen(network, address string) (Listener, error)
The Listen
function accepts the following parameters:
network
: The named network for communication, e.g., TCP, UDP, IP, etc.
address
: The address of the host server to listen on for connections.
Note: The list of supported networks and rules for their corresponding hosts can be found here.
The Listen
function returns a Listener object that represents a server and an error
object.
If the Listen
function is able to listen on the specified address successfully, the error
object has a value of nil
.
The code below shows how the Listen
function works in Go.
package main// import necessary packagesimport ("net""fmt")func main(){// initialize the address port number of the serverport := ":8000"// Set up a listener on port 8080 for tcp connectionsln, err := net.Listen("tcp", port)// check if server was successfully createdif err != nil {fmt.Println("The following error occured", err)} else {fmt.Println("The listener object has been created:", ln)}}
net
and fmt
packages.port
number on which the Listen
function will listen.Listen
function to create a server that listens for tcp
connections on the specified port.err
will be nil
, and the corresponding message will be output. Otherwise, the if
statement in line 18 will detect the error and print the relevant message if an error occurs.