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
}