dongse7261 2014-10-13 17:29
浏览 55
已采纳

限制连接到网络服务的客户端数量

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()
    }()
    ...
    ...
}
  • 写回答

1条回答 默认 最新

  • douniao7308 2014-10-14 11:26
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)