To listen and handle incoming requests, the net package provides the net.Listen
function:
func Listen(network, laddr string) (net.Listener, error)
This function requires two parameters: network, indicating the protocol for incoming requests, and laddr, representing the local address at which the server will be initiated. The protocol must be one of the following values: "tcp", "tcp4", "tcp6", "unix", or "unixpacket". The local address can solely include a port number, for instance, ":8080". In this scenario, the application will serve all incoming connections.
Upon success, the function returns a net.Listener
interface object, which encapsulates the functionality for handling incoming connections. Depending on the protocol used, the returned Listener object may be of type net.TCPListener or net.UnixListener (both types implement the net.Listener
interface).
The primary methods offered by net.Listener
are Accept()
(accepts an incoming connection) and Close()
(closes the connection).
Create a new file let's call it server.go:
package main
import (
"fmt"
"net"
)
func main() {
msg := "Hi from the Server"
list, err := net.Listen("tcp", ":2345")
if err != nil {
fmt.Println("Error:", err)
return
}
defer list.Close()
fmt.Println("Server is running..")
for {
topCon, err := list.Accept()
if err != nil {
fmt.Println("Error:", err)
return
}
topCon.Write([]byte(msg))
topCon.Close()
}
}
Initially, the net.Listen("tcp", ":2345")
function configures the server to listen on port 2345 for incoming connections via TCP. Upon invoking this function, the server initiates and becomes ready to accept connections. Subsequently, within an infinite for loop, we utilize listener.Accept()
to fetch incoming connections. This method returns a net.Conn
object, representing the connected client. This connection can then be processed accordingly. For instance, by utilizing the Write method, we can send a message to the client. Given that this method expects a byte slice, any messages need to be converted into a byte slice: topCon.Write([]byte(msg))
.
To test this, we'll need to define a client.go:
package main
import (
"fmt"
"os"
"net"
"io"
)
func main() {
topCon, err := net.Dial("tcp", "127.0.0.1:2345")
if err != nil {
fmt.Println(err)
return
}
defer topCon.Close()
io.Copy(os.Stdout, topCon)
fmt.Println("\n Connection established!")
}
Here we use the same port as the one used in the server, which is 2345.
If you start the server will get:
Server is running..
And we run the client:
Hi from the Server
Connection established!