Skip to content

Commit

Permalink
fix: Fix panic: send on closed channel
Browse files Browse the repository at this point in the history
```
device                           broker
------------------------------------------------------
dev.br.register <- dev

dev.br.unregister <- dev
                                 handle unregister
                                       c.Close()

                                 handle register
                                       c.WriteMsg(msgTypeRegister, append([]byte{err}, msg...))
                                            dev.send <- append(b, data...)

```

Signed-off-by: Jianhui Zhao <[email protected]>
  • Loading branch information
zhaojh329 committed Nov 23, 2024
1 parent 26328a6 commit 7dd174d
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 2 deletions.
4 changes: 4 additions & 0 deletions broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ func (br *broker) run() {
for {
select {
case c := <-br.register:
if c.Closed() {
break
}

devid := c.DeviceID()

if c.IsDevice() {
Expand Down
2 changes: 2 additions & 0 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ type Client interface {
IsDevice() bool

Close()

Closed() bool
}
7 changes: 6 additions & 1 deletion device.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,15 @@ func (dev *device) WriteMsg(typ int, data []byte) {
dev.send <- append(b, data...)
}

func (dev *device) Closed() bool {
return atomic.LoadUint32(&dev.closed) == 1
}

func (dev *device) Close() {
if atomic.LoadUint32(&dev.closed) == 1 {
if dev.Closed() {
return
}

atomic.StoreUint32(&dev.closed, 1)

log.Debug().Msgf("Device '%s' disconnected", dev.conn.RemoteAddr())
Expand Down
7 changes: 6 additions & 1 deletion user.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,15 @@ func (u *user) WriteMsg(typ int, data []byte) {
}
}

func (u *user) Closed() bool {
return atomic.LoadUint32(&u.closed) == 1
}

func (u *user) Close() {
if atomic.LoadUint32(&u.closed) == 1 {
if u.Closed() {
return
}

atomic.StoreUint32(&u.closed, 1)

u.conn.Close()
Expand Down

0 comments on commit 7dd174d

Please sign in to comment.