Allenxuxu / gev

🚀Gev is a lightweight, fast non-blocking TCP network library / websocket server based on Reactor mode. Support custom protocols to quickly and easily build high-performance servers.
MIT License
1.72k stars 193 forks source link

客户端发出主动关闭请求时无法触发onClose #78

Closed cs-charles closed 3 years ago

cs-charles commented 3 years ago

在案例控制服务端的最大连接数代码中,通过OnConnect事件和onClose事件来控制链接计数器。经本人测试后,如果是客户端发送header.OpCode为ws.OpClose后,服务端会调用c.ShutdownWrite()方法来关闭连接,同时设置c.connected.Set(false)。而onClose方法在响应关闭连接的事件回调后会触发如下逻辑,由于c.connected在前面已经被设置成了false,所以并不会执行onClose()方法。导致服务端的连接计数器不准确。

func (c *Connection) handleClose(fd int) {
    if c.connected.Get() {
        c.connected.Set(false)
        c.loop.DeleteFdInLoop(fd)

        c.callBack.OnClose(c)
        if err := unix.Close(fd); err != nil {
            log.Error("[close fd]", err)
        }

        ringbuffer.PutInPool(c.inBuffer)
        ringbuffer.PutInPool(c.outBuffer)
    }
}
Allenxuxu commented 3 years ago

这边确实有问题,ShutdownWrite 方法内部理论上不需要 c.connected.Set(false),这样也就应该没有这个问题了。

Allenxuxu commented 3 years ago

如果你有空,可以在 PR 加个单测复现下这个问题,应该删除这行就可以 Fix 这个问题了 https://github.com/Allenxuxu/gev/blob/7ac1dc183d41d1503378a0b9edc2cdc180be9487/connection/connection.go#L142

Allenxuxu commented 3 years ago

@cs-charles 这个bug 已经修复了,感谢指出