【问题标题】:Limit number of clients connected to a Network Service限制连接到网络服务的客户端数量
【发布时间】:2014-10-14 19:26:55
【问题描述】:

如何限制连接到我的服务的客户端数量? 我尝试了一个简单的计数器,但是如果客户端没有关闭就退出 他们的联系我不知道怎么弄的。

请有人给我一些想法以便得到它?

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()
    }()
    ...
    ...
}

【问题讨论】:

    标签: sockets go


    【解决方案1】:

    实际上可能是您没有与我们共享的代码中的问题(那些...)

    连接将退出 - 迟早。假设是在您的连接处理程序中您必须执行一些读/写操作,因此最好的方法是使用读/写超时(截止日期)来引发您将根据需要处理的错误。

    请检查SetReadDeadline/SetWriteDeadline 在文档http://golang.org/pkg/net/#IPConn.SetReadDeadline 中的使用情况或在此答案中使用的https://stackoverflow.com/a/12741495/93767

    修复处理程序部分后,您可以毫无问题地使用客户端计数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 2019-09-22
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多