// create a listener on port 8080 listener, _ := net.Listen("tcp", ":8080") // set deadline for the listener listener.SetDeadline(time.Now().Add(time.Second * 10)) // accept connections until deadline for { conn, err := listener.Accept() if err != nil { fmt.Printf("Error accepting connection: %s\n", err.Error()) break } // do something with the connection... }
// create a listener on port 8888 listener, _ := net.Listen("tcp", ":8888") // set deadline for the listener listener.SetDeadline(time.Now().Add(time.Second * 5)) // read data from connections until deadline for { conn, err := listener.Accept() if err != nil { fmt.Printf("Error accepting connection: %s\n", err.Error()) break } // set deadline for the connection conn.SetDeadline(time.Now().Add(time.Second * 2)) // read from the connection buf := make([]byte, 1024) _, err = conn.Read(buf) if err != nil { fmt.Printf("Error reading data from connection: %s\n", err.Error()) } // do something with the data... }This code creates a TCP listener on port 8888 and sets a deadline of 5 seconds. It accepts connections and sets a deadline of 2 seconds for each connection. After reading data from the connection, it can perform some action with the data. The Go net package library provides the SetDeadline method for TCPListener, which is used in the aforementioned examples.