How Accept() works exactly?

func main() {
	li, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatalln(err)
	}
	defer li.Close()

	for {
		conn, err := li.Accept()
		if err != nil {
			log.Println(err)
			continue
		}
		go handle(conn)
	}
}

func handle(conn net.Conn) {
	scanner := bufio.NewScanner(conn)
	for scanner.Scan() {
		ln := scanner.Text()
		fmt.Println(ln)
	}
	defer conn.Close()
}

In here, Accept() enables to connection from client. One thing I want to know is how Accept() works exactly? In the net/http package, there are only function name and return value. Even though I didn’t define how it works, how does it work?

Below is the explanation about Accept() of net package

type Listener interface {
// Accept waits for and returns the next connection to the listener.
Accept() (Conn, error)

// Close closes the listener.
// Any blocked Accept operations will be unblocked and return errors.
Close() error

// Addr returns the listener's network address.
Addr() Addr

}

Accept is a system call from the Operating System. It is just wrapped by the Go runtime so that it can be polled later for reading and writing.

If you want to know more about accept, you can read the manual page: http://man7.org/linux/man-pages/man2/accept.2.html

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.