Skip to content

Commit

Permalink
fix: panic: send on closed channel
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <[email protected]>
  • Loading branch information
zhaojh329 committed Apr 12, 2022
1 parent 03b976a commit 87ac722
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
35 changes: 23 additions & 12 deletions broker.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,13 @@ func (br *broker) run() {
}

c.WriteMsg(msgTypeRegister, append([]byte{err}, msg...))

if err > 0 {
// ensure the last packet was sent
time.AfterFunc(time.Millisecond*100, func() {
dev.Close()
})
}
} else {
if dev, ok := br.devices[devid]; ok {
sid := utils.GenUniqueID("sid")
Expand Down Expand Up @@ -125,19 +132,11 @@ func (br *broker) run() {

c.Close()

if !c.IsDevice() {
sid := c.(*user).sid

if _, ok := br.sessions[sid]; ok {
delete(br.sessions, sid)

if dev, ok := br.devices[devid]; ok {
dev.WriteMsg(msgTypeLogout, []byte(sid))
}

log.Info().Msg("Delete session: " + sid)
if c.IsDevice() {
if !c.(*device).registered {
break
}
} else if c.(*device).registered {

delete(br.devices, devid)

for sid, s := range br.sessions {
Expand All @@ -149,6 +148,18 @@ func (br *broker) run() {
}

log.Info().Msgf("Device '%s' unregistered", devid)
} else {
sid := c.(*user).sid

if _, ok := br.sessions[sid]; ok {
delete(br.sessions, sid)

if dev, ok := br.devices[devid]; ok {
dev.WriteMsg(msgTypeLogout, []byte(sid))
}

log.Info().Msg("Delete session: " + sid)
}
}

case msg := <-br.loginAck:
Expand Down
7 changes: 2 additions & 5 deletions device.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ func parseHeartbeat(dev *device, b []byte) {
func (dev *device) readLoop() {
defer func() {
dev.br.unregister <- dev
dev.conn.Close()
}()

br := bufio.NewReader(dev.conn)
Expand Down Expand Up @@ -303,7 +302,7 @@ func (dev *device) writeLoop() {

defer func() {
ticker.Stop()
dev.conn.Close()
dev.br.unregister <- dev
}()

ninactive := 0
Expand All @@ -325,15 +324,13 @@ func (dev *device) writeLoop() {
case <-ticker.C:
now := time.Now()
if now.Sub(dev.active) > heartbeatInterval*3/2 {
if !dev.registered {
dev.Close()
if dev.id == "" {
return
}

log.Error().Msgf("Inactive device in long time: %s", dev.id)
if ninactive > 1 {
log.Error().Msgf("Inactive 3 times, now kill it: %s", dev.id)
dev.Close()
return
}
ninactive = ninactive + 1
Expand Down

0 comments on commit 87ac722

Please sign in to comment.