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.

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

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用