How can I limit the number of clients connected to my service? I tried with a simple counter, but if a client exits without close their connection I don't have how get it.
Please could somebody give me ideas in order to get it?
const MAX_CLIENTS = 5
var ConnectedClients int
func main() {
ConnectedClients = 0
server, err := net.Listen(CONN_TYPE, net.JoinHostPort(CONN_HOST, CONN_PORT))
if err != nil {
fmt.Println("Error Listening", err.Error())
os.Exit(1)
}
defer server.Close()
fmt.Println("Listening on ", net.JoinHostPort(CONN_HOST, CONN_PORT))
for {
conn, err := server.Accept()
if err != nil {
fmt.Println("Error acepting: ", err.Error())
os.Exit(1)
}
ConnectedClients += 1
fmt.Println("Connected with:", conn.RemoteAddr())
fmt.Println("Clients:", ConnectedClients)
if ConnectedClients > MAX_CLIENTS {
fmt.Println("Limit reached! Disconnecting:", conn.RemoteAddr())
conn.Close()
}
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
//This defer will never run.... :-(
defer func() {
fmt.Println("Connection closed with client:", conn.RemoteAddr())
ConnectedClients -= 1
conn.Close()
}()
...
...
}