Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix bug: [Panic]: send on closed channel #318

Merged
merged 1 commit into from
Apr 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 10 additions & 25 deletions znet/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,6 @@ type Connection struct {
// (保护当前property的锁)
propertyLock sync.Mutex

// The current connection's close state
// (当前连接的关闭状态)
closed int32

// Which Connection Manager the current connection belongs to
// (当前链接是属于哪个Connection Manager的)
connManager ziface.IConnManager
Expand Down Expand Up @@ -127,7 +123,6 @@ func newServerConn(server ziface.IServer, conn net.Conn, connID uint64) ziface.I
conn: conn,
connID: connID,
connIdStr: strconv.FormatUint(connID, 10),
closed: 0,
startWriterFlag: 0,
msgBuffChan: nil,
property: nil,
Expand Down Expand Up @@ -165,7 +160,6 @@ func newClientConn(client ziface.IClient, conn net.Conn) ziface.IConnection {
conn: conn,
connID: 0, // client ignore
connIdStr: "", // client ignore
closed: 0,
startWriterFlag: 0,
msgBuffChan: nil,
property: nil,
Expand Down Expand Up @@ -393,10 +387,15 @@ func (c *Connection) SendToQueue(data []byte) error {

// Send timeout
select {
case <-idleTimeout.C:
return errors.New("send buff msg timeout")
case c.msgBuffChan <- data:
return nil
case <-c.ctx.Done():
return errors.New("connection closed when send buff msg")
default:
select {
case <-idleTimeout.C:
return errors.New("send buff msg timeout")
case c.msgBuffChan <- data:
return nil
}
}
}

Expand Down Expand Up @@ -466,16 +465,6 @@ func (c *Connection) Context() context.Context {
}

func (c *Connection) finalizer() {
// If the connection has already been closed
if c.isClosed() == true {
return
}

//set closed
if !c.setClose() {
return
}

// Call the callback function registered by the user when closing the connection if it exists
// (如果用户注册了该链接的 关闭回调业务,那么在此刻应该显示调用)
c.callOnConnStop()
Expand Down Expand Up @@ -560,11 +549,7 @@ func (c *Connection) GetMsgHandler() ziface.IMsgHandle {
}

func (c *Connection) isClosed() bool {
return atomic.LoadInt32(&c.closed) != 0
}

func (c *Connection) setClose() bool {
return atomic.CompareAndSwapInt32(&c.closed, 0, 1)
return c.ctx.Err() != nil
}

func (c *Connection) setStartWriterFlag() bool {
Expand Down
Loading