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()
}()
...
...
}
Actually it might be the issue in the code you have not shared with us (those ...)
Connection will exit - sooner or later. The assumption is that in your connection handler you have to do some read/write operations, so the best way forward would be use read/write timeout (deadlines) to raise errors which you going to handle as needed.
Please, check the use of SetReadDeadline/SetWriteDeadline
in documentation http://golang.org/pkg/net/#IPConn.SetReadDeadline or as used in this answer - https://stackoverflow.com/a/12741495/93767
Once you fix the handler part you can use client counting without any issues.