如何限制连接到我的服务的客户端数量?我尝试了一个简单的计数器,但是如果客户端在没有关闭连接的情况下退出,我不知道如何得到它。请问有人可以给我一些想法以获得它吗?const MAX_CLIENTS = 5var ConnectedClients intfunc 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() }() ... ...}
1 回答
- 1 回答
- 0 关注
- 219 浏览
添加回答
举报
0/150
提交
取消