fhmq/hmq

功耗过高的问题

Closed this issue · 2 comments

mylxy commented

**
image
**

设备端功耗比较高,抓包看了一下,服务器与设备建立连接之后,每隔1分钟向设备发送消息,有什么作用,能禁用吗?

是心跳设备,不能关闭,对应的是KeepAlive参数,默认是60s,可以在客户端配置修改

mylxy commented

MQTT的心跳是ping Request &ping Response,自身保持,不依赖于tcp的keepAlive,要禁用掉,经测试设备正常,功耗明显降低

// go底层代码
func (ln *TCPListener) accept() (*TCPConn, error) {
	fd, err := ln.fd.accept()
	if err != nil {
		return nil, err
	}
	tc := newTCPConn(fd)
	if ln.lc.KeepAlive >= 0 {
		setKeepAlive(fd, true)
		ka := ln.lc.KeepAlive
		if ln.lc.KeepAlive == 0 {
			ka = defaultTCPKeepAlive
		}
		setKeepAlivePeriod(fd, ka)
	}
	return tc, nil
}

//hmq
func (b *Broker) StartClientListening(Tls bool) {
	var hp string
	var err error
	var l net.Listener
	if Tls {
		hp = b.config.TlsHost + ":" + b.config.TlsPort
		l, err = tls.Listen("tcp", hp, b.tlsConfig)
		log.Info("Start TLS Listening client on ", zap.String("hp", hp))
	} else {
		hp := b.config.Host + ":" + b.config.Port
		// start 删除掉TCP的心跳机制
		//l, err = net.Listen("tcp", hp)
		lc := net.ListenConfig{
			KeepAlive: -1,
		}
		l, err = lc.Listen(context.Background(), "tcp", hp)
		// end
		log.Info("Start Listening client on ", zap.String("hp", hp))
	}
	if err != nil {
		log.Error("Error listening on ", zap.Error(err))
		return
	}
	tmpDelay := 10 * ACCEPT_MIN_SLEEP
	for {
		conn, err := l.Accept()
		if err != nil {
			if ne, ok := err.(net.Error); ok && ne.Temporary() {
				log.Error("Temporary Client Accept Error(%v), sleeping %dms",
					zap.Error(ne), zap.Duration("sleeping", tmpDelay/time.Millisecond))
				time.Sleep(tmpDelay)
				tmpDelay *= 2
				if tmpDelay > ACCEPT_MAX_SLEEP {
					tmpDelay = ACCEPT_MAX_SLEEP
				}
			} else {
				log.Error("Accept error: %v", zap.Error(err))
			}
			continue
		}
		tmpDelay = ACCEPT_MIN_SLEEP
		go b.handleConnection(CLIENT, conn)

	}
}